2010-04-29 63 views
5

mochijson2我有了一些JSON數據的VAR:解碼JSON在二郎

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

使用mochijson2,我對數據進行解碼:

Struct = mochijson2:decode(A). 

現在我有這樣的:

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

我正在嘗試閱讀(例如)「job」或「id」。

我試過使用struct.get_value,但它似乎不工作。

任何想法?

回答

13

的數據是{結構,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

1

添加到給出的答案前面有在mochiweb上,json(視頻)也是一個不錯的tutorial

2

這是另一種訪問數據的方法。爲便於使用,使用records syntax

-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時只是另一種選擇。我個人更喜歡這個語法。

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中提取值可以是任何簡單。

1

我最喜歡handeling 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. 

這與可以有意想不到的傳入數據時,特別是有很多好處形狀。