【问题标题】:How to use mochijson to encode data structure in erlang?如何使用 mochijson 对 erlang 中的数据结构进行编码?
【发布时间】:2010-11-10 13:11:52
【问题描述】:

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

【问题讨论】:

    标签: json erlang mochiweb


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:
      T6={struct, [{hello,"asdf"},{from,"1"},{to, {a,"aa"}} ]}.
      

      应该是:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-13
        • 1970-01-01
        相关资源
        最近更新 更多