Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
Jon Romero Avatar asked Apr 29 '10 17:04

Jon Romero


3 Answers

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

like image 87
scatterbrain Avatar answered Oct 29 '22 20:10

scatterbrain


Another helper function to access json structure:

jsonobj({struct,List}) ->
    fun({contains,Key}) ->
        lists:keymember(Key,1,List);
    ({raw,Key}) ->
        {_,Ret} = lists:keyfind(Key,1,List),Ret;
    (Key) ->
        {_,Ret} = lists:keyfind(Key,1,List),
        jsonobj(Ret)
    end;
jsonobj(List) when is_list(List) ->
    fun(len) ->
        length(List);
    (Index) ->
        jsonobj(lists:nth(Index,List))
    end;
jsonobj(Obj) -> Obj.

Usage:

1> A=mochijson2:decode(<<"{\"job\": {\"id\": \"1\", \"ids\": [4,5,6], \"isok\": true}}">>).
2> B=jsonobj(A).
3> B(<<"job">>).
#Fun<jsonutils.1.33002110>
4> (B(<<"job">>))(<<"id">>).
1
5> (B(<<"job">>))(<<"ids">>).
#Fun<jsonutils.1.9495087>
6> (B(<<"job">>))({raw,<<"ids">>}).
[4,5,6]
7> ((B(<<"job">>))(<<"ids">>))(1).
4
8> B({raw,<<"job">>}).
{struct,[{<<"id">>,<<"1">>},
               {<<"ids">>,[1,2,3]},
               {<<"isok">>,true}]}
9> B({contains,<<"job">>}).
true
10> B({contains,<<"something">>}).
false
11> ((B(<<"job">>))(<<"ids">>))(len)
3

I don't think extracting values from json can be any simpler.

like image 40
yetihehe Avatar answered Oct 29 '22 19:10

yetihehe


Here is another method of accessing the data. Uses records syntax for ease of use.

-record(struct, {lst=[]}).

A = <<"{\"job\": {\"id\": \"1\"}}">>,
Struct = mochijson2:decode(A), 
Job = proplists:get_value(<<"job">>, Struct#struct.lst),
Id = proplists:get_value(<<"id">>, Job#struct.lst),

Does exactly the same thing as the answer using records instead. Just another option when using mochijson2. I personally like this syntax better.

like image 2
Luigimax Avatar answered Oct 29 '22 18:10

Luigimax