用erlang的Mochijson2解码JSON
-
02-10-2019 - |
题
我有一个有一些JSON数据的VAR:
A = <<"{\"job\": {\"id\": \"1\"}}">>.
使用Mochijson2,我解码数据:
Struct = mochijson2:decode(A).
现在我有了:
{struct,[{<<"job">>,{struct,[{<<"id">>,<<"1">>}]}}]}
我正在尝试阅读(例如)“作业”或“ ID”。
我尝试使用struct.get_value,但似乎不起作用。
有任何想法吗?
解决方案
数据采用{struct,preplist()}格式,因此您要做的是:
{struct, JsonData} = Struct,
{struct, Job} = proplists:get_value(<<"job">>, JsonData),
Id = proplists:get_value(<<"id">>, Job),
其他提示
访问JSON结构的另一个辅助功能:
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.
用法:
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
我认为从JSON中提取值不会更简单。
这是访问数据的另一种方法。用途 记录语法 易用。
-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),
与使用记录完全相同的答案。使用Mochijson2时只是另一个选择。我个人更喜欢这种语法。
添加到前面给出的答案也很不错 教程 在Mochiweb上,JSON(视频)。
我最喜欢的摩西森数据的方法是用哈希地图替换所有结构,然后它们可以完全匹配。为此,我写了这个易于理解的功能:
structs_to_maps({struct, Props}) when is_list(Props) ->
lists:foldl(
fun({Key, Val}, Map) ->
Map#{Key => structs_to_maps(Val)}
end,
#{},
Props
);
structs_to_maps(Vals) when is_list(Vals) ->
lists:map(
fun(Val) ->
structs_to_maps(Val)
end,
Vals
);
structs_to_maps(Val) ->
Val.
这是如何使用它的示例:
do() ->
A = <<"{\"job\": {\"id\": \"1\"}}">>,
Data = structs_to_maps(mochijson2:decode(A)),
#{<<"job">> := #{<<"id">> := Id}} = Data,
Id.
这具有许多优势,尤其是在处理可能具有意外形态的数据时。
不隶属于 StackOverflow