Jon Romero Jon Romero - 2 months ago 24
JSON Question

Decode JSON with mochijson2 in Erlang

I have a var that has some JSON data:

A = <<"{\"job\": {\"id\": \"1\"}}">>.


Using mochijson2, I decode the data:

Struct = mochijson2:decode(A).


And now I have this:

{struct,[{<<"job">>,{struct,[{<<"id">>,<<"1">>}]}}]}


I am trying to read (for example), "job" or "id".

I tried using struct.get_value but it doesn't seem to work.

Any ideas?

Answer

The data is in {struct, proplist()} format, so here's what you do:

{struct, JsonData} = Struct,
{struct, Job} = proplists:get_value(<<"job">>, JsonData),
Id = proplists:get_value(<<"id">>, Job),

You can read more about proplists at: http://www.erlang.org/doc/man/proplists.html