如何使用mochijson在erlang中编码数据结构?

2024-01-26

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

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 示例! https://stackoverflow.com/questions/1000046/mochijson2-examples

or

开始在 Erlang 上开发 Web 应用程序的视频教程 https://web.archive.org/web/20150924043751/http://beebole.com/blog/erlang/tutorial-web-application-erlang/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用mochijson在erlang中编码数据结构? 的相关文章

随机推荐