如何使用mochijson对erlang中的数据结构进行编码?

时间:2009-07-14 05:30:41

标签: json erlang mochiweb

我使用的是mochiweb,我不知道如何使用它的json编码器来处理复杂的数据结构。 mochijson和mochijson2之间的区别是什么?有什么好的例子吗?我总是遇到以下错误:

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

2 个答案:

答案 0 :(得分: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!

Video Tutorial To Start Developing Web Applications on Erlang

答案 1 :(得分:4)

T6={struct, [{hello,"asdf"},{from,"1"},{to, {a,"aa"}} ]}.

应改为:

T6={struct, [{hello,"asdf"},{from,"1"},{to, {struct, [{a,"aa"}]}} ]}.

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