5

我有一个包含一些 JSON 数据的 var:

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

使用 mochijson2,我解码数据:

 Struct = mochijson2:decode(A). 

现在我有了这个:

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

我正在尝试阅读(例如)“job”或“id”。

我尝试使用 struct.get_value 但它似乎不起作用。

有任何想法吗?

4

5 回答 5

13

数据采用 {struct, proplist()} 格式,因此您可以执行以下操作:

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

你可以阅读更多关于 proplists 的信息:http ://www.erlang.org/doc/man/proplists.html

于 2010-04-29T20:12:20.203 回答
5

另一个访问 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 中提取值会更简单。

于 2012-11-29T20:28:24.347 回答
2

这是访问数据的另一种方法。使用记录语法以便于使用。

-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 时的另一种选择。我个人更喜欢这种语法。

于 2012-08-18T08:20:01.503 回答
1

除了前面给出的答案之外,还有一个关于 mochiweb的很好的教程,json(视频)。

于 2010-04-30T01:35:25.070 回答
1

我最喜欢的处理 mochijson 数据的方法是用哈希映射替换所有结构,之后它们可以进行干净的模式匹配。为此,我编写了这个易于理解的函数:

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.

这有很多优点,尤其是在处理可能具有意外形状的传入数据时。

于 2016-09-22T13:50:46.773 回答