Decode JSON with mochijson2 in Erlang

后端 未结 5 912
灰色年华
灰色年华 2021-02-10 07:28

I have a var that has some JSON data:

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

Using mochijson2, I decode the data:

5条回答
  •  心在旅途
    2021-02-10 08:15

    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
    4> (B(<<"job">>))(<<"id">>).
    1
    5> (B(<<"job">>))(<<"ids">>).
    #Fun
    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.

提交回复
热议问题