1

我有两个对象,我想将它们捆绑并发送到一个数组中,用 mochijson 编码为 JSON。他们是:

> Book0 = {struct, [{"title", "a book"}, {"id", "1"}]}.      
> Book1 = {struct, [{"title", "another book"}, {"id", "2"}]}.

然而,

> mochijson:encode({struct, [{"books", [Book0, Book1]}]}).
** exception exit: {json_encode,{bad_char,{struct,[{"title","a book"},
                                                   {"id","1"}]}}}
     in function  mochijson:json_encode_string_unicode_1/1 (src/mochijson.erl, line 203)
     in call from mochijson:json_encode_string_unicode/1 (src/mochijson.erl, line 190)
     in call from mochijson:'-json_encode_proplist/2-fun-0-'/3 (src/mochijson.erl, line 151)
     in call from lists:foldl/3 (lists.erl, line 1197)
     in call from mochijson:json_encode_proplist/2 (src/mochijson.erl, line 154)

如何为 mochijson 构建数据?我知道这篇文章,但遗憾的是,它没有涵盖对象数组。

4

3 回答 3

4

mochijson:encode({struct, [{"books", { array , [Book0, Book1]}}]})。

[123,"\"books\"",58,
 [91,
  [123,"\"title\"",58,"\"a book\"",44,"\"id\"",58,"\"1\"",125],
  44,
  [123,"\"title\"",58,"\"another book\"",44,"\"id\"",58,
   "\"2\"",125],
  93],
 125]

但普遍的共识似乎确实是:“使用 mochijson2”(在有和没有的情况下都可以正确工作array)。

于 2012-03-07T23:58:07.863 回答
2

经过一番深入研究后,最好的答案是:除非您有充分的理由不这样做,否则更喜欢 mochijson2。

于 2012-03-07T23:11:32.537 回答
1

mochijson2 也比 mochijson 快。

于 2012-03-13T11:48:17.600 回答