1

I have two objects that I'd like to bundle up and ship in an array, encoded as JSON with mochijson. They are:

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

However,

> 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)

How do I structure my data for mochijson? I'm aware of this article but it, sadly, does not cover arrays of objects.

Community
  • 1
  • 1
troutwine
  • 3,721
  • 3
  • 28
  • 62

3 Answers3

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]

But the general consensus indeed seems to be: "use mochijson2" (which would correctly work for both cases with and without array).

Ed'ka
  • 6,595
  • 29
  • 30
  • most correctly `mochijson2:encode({struct,[<<"books">>,[Book0,Book1]]}).` where: `Book0 = {struct, [{<<"title">>, <<"a book">>}, {<<"id">>, <<"1">>}]}.` and `Book1 = {struct, [{<<"title">>, <<"another book">>}, {<<"id">>, <<"2">>}]}.` Note that `mochijson2` is a newer implementation than `mochijson` – Muzaaya Joshua Mar 08 '12 at 12:48
  • With mochijson2, we can drop `struct` keyword and JSON object as list of `{Key, Value}`s. – shino Mar 08 '12 at 13:58
  • 2
    If you're doing a lot of encoding/decoding looking for something faster than mochiweb I'd recommend [jiffy](https://github.com/davisp/jiffy). It's a set of nifs that uses a similar structure to mochijson for JSON. The main difference in structure is you don't need the `struct` and `array` atoms in the tuples. E.g.) instead of the above it's just be `{[{"books",[Book0, Book1]}]}`. – Jeremy Raymond Mar 09 '12 at 01:30
2

The best answer, after a bit of source diving, is: prefer mochijson2 unless you have an excellent reason not to.

troutwine
  • 3,721
  • 3
  • 28
  • 62
1

mochijson2 is also faster then mochijson.

Jakub Oboza
  • 5,291
  • 1
  • 19
  • 10