6

我正在使用 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
4

2 回答 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 示例!

或者

开始在 Erlang 上开发 Web 应用程序的视频教程

于 2009-07-14T18:26:29.847 回答
4
T6={struct, [{hello,"asdf"},{from,"1"},{to, {a,"aa"}} ]}.

应该改为:

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

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

于 2010-09-29T03:50:54.167 回答