2009-07-14 62 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”}]}}]}应该是

嵌套结构需要与顶级对象具有相同的“结构”风格。