2009-07-14 61 views
6

我正在使用mochiweb,我不知道如何使用它的json編碼器來處理複雜的數據結構。 mochijson和mochijson2有什麼區別?有沒有什麼好的例子?我總是得到以下錯誤:如何使用mochijson在erlang中編碼數據結構?

46> T6={struct,[{hello,"asdf"},{from,"1"},{to,{a,"aa"}}]}. 
{struct,[{hello,"asdf"},{from,"1"},{to,{a,"aa"}}]} 
47> mochijson2:encode(T6).         
** exception exit: {json_encode,{bad_term,{a,"aa"}}} 
    in function mochijson2:json_encode/2 
    in call from mochijson2:'-json_encode_proplist/2-fun-0-'/3 
    in call from lists:foldl/3 
    in call from mochijson2:json_encode_proplist/2 


39> T3={struct,[{hello,"asdf"},{[{from,"1"},{to,"2"}]}]}. 
{struct,[{hello,"asdf"},{[{from,"1"},{to,"2"}]}]} 
40> mochijson:encode(T3).         
** exception error: no function clause matching mochijson:'-json_encode_proplist/2-fun-0-'({[{from,"1"},{to,"2"}]}, 
                          [44,"\"asdf\"",58,"\"hello\"",123], 
                          {encoder,unicode,null}) 
    in function lists:foldl/3 
    in call from mochijson:json_encode_proplist/2 

回答

11

mochijson2用字符串作爲二進制文件列表作爲數組的作品,只有解碼UTF-8。 mochijson解碼並編碼unicode代碼點。

要創建一個深刻的結構我做了以下內容:

2> L = {struct, [{key2, [192]}]}. 
{struct,[{key2,"?"}]} 
3> 
3> L2 = {struct, [{key, L}]}. 
{struct,[{key,{struct,[{key2,"?"}]}}]} 
4> 
4> mochijson:encode(L2). 
[123,"\"key\"",58, 
[123,"\"key2\"",58,[34,"\\u00c0",34],125], 
125] 

所以,如果你遞歸創建使用列表,那麼你會沒事的你的數據結構。我不確定爲什麼深層次的結構不被支持,但他們似乎不是,至少不是你嘗試創建它們的方式。也許別人知道一個更聰明的方式來做到這一點。

也可以檢查出這個線程:mochijson2 examples!

http://beebole.com/en/blog/erlang/tutorial-web-application-erlang/

4

T6 = {結構,[{你好 「ASDF」},{從 「1」},{到,{a,「aa」}}]}。 T6 = {struct,[{hello,「asdf」},{from,「1」},{to,{struct,[{a,「aa」}]}}]}應該是

嵌套結構需要與頂級對象具有相同的「結構」風格。