mochijson2 接口使用

2016-09-01 10:02:00
admin
原创 4491
摘要:传闻erlang otp会提供json数据处理库,有些讨论但不见下文,暂且用mochiweb的mochijson2.erl吧:

decode
test_mochijson2_decode() ->
    Sjson = "{\"id1\":[\"str1\", \"str2\", \"str3\"], \"id2\":[\"str4\", \"str5\"]}",
    Mjson = mochijson2:decode(Sjson),
    io:fwrite("test_json:test_mochijson2/0:Mjson=~p~n",[Mjson]).

>>> output <<<
test_json:test_mochijson2/0:Mjson={struct,
                                      [{<<"id1">>,
                                        [<<"str1">>,<<"str2">>,<<"str3">>]},
                                       {<<"id2">>,[<<"str4">>,<<"str5">>]}]}

mochijson2:decode将json字符串转化为erlang数据格式,随后可以根据需要进行match或提取。

encode
test_mochijson2_encode() ->
    Mjson = {struct,
             [{<<"id1">>, [<<"str1">>,<<"str2">>,<<"str3">>]},
              {<<"id2">>, [<<"str4">>,<<"str5">>]}]},
    Sjson = binary_to_list(list_to_binary(mochijson2:encode(Mjson))),
    io:fwrite("test_json:test_mochijson2/0:Sjson2=~s~n",[Sjson]).

>>> output <<<
test_json:test_mochijson2/0:Sjson2={"id1":["str1","str2","str3"],"id2":["str4","str5"]}

与decode相对应,只要提供与mochijson2:decode返回相一致的erlang数据格式,就可以通过mochijson2:encode得到json字符串。需要注意的是字符串形式key或value都需要使用binary格式,这是因为字符串在erlang内部以list表达,mochijson2会对list每个元素进行处理,而用binary则将字符串作为了一个整体。

see also
JSON
JSONLint - The JSON Validator.
JSONView :: Add-ons for Firefox
Erlang JSON libraries: serialization performance? - Stack Overflow
Erlang Forum - Trap Exit - View topic - Which Erlang JSON parser?