How to use mochijson to encode data structure in erlang?

Mickey Shine picture Mickey Shine · Jul 14, 2009 · Viewed 7.9k times · Source

I am using mochiweb and I don't know how to use its json encoder to deal with complex data structure. What's the differences between mochijson and mochijson2? Is there any good example? I always get the following errors:

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

Answer

Joshua Noble picture Joshua Noble · Jul 14, 2009

mochijson2 works with strings as binaries, lists as arrays, and only decodes UTF-8. mochijson decodes and encodes unicode code points.

To create a deep struct I did the following:

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]

So if you recursively create your data structure using lists then you'll be fine. I'm not sure why deep structs aren't supported, but they don't seem to be, at least not the way you're trying to create them. Maybe someone else knows a more clever way to do this.

You can also check out this thread: mochijson2 examples!

or

Video Tutorial To Start Developing Web Applications on Erlang