mochijson2 examples!
Asked Answered
W

4

16

I'm a two-week old infant with regards to Erlang and Mochiweb. Earlier I had a system running on PHP and soon I realised that it wasn't going to be able to handle the kind of load I was expecting. So I decided to switch the backend to a Mochiweb based server. Right now I need to know how to implement JSON with Mochiweb. I'm fully aware of the existense of mochijson2 library, but being a beginner, I can't get around to figuring out how to use it. Could someone point me to some place where I can find examples of using this library or any other json library in erlang?

Wageworker answered 16/6, 2009 at 7:43 Comment(0)
J
9

The mochijson2 API essentially consists of just two functions, which (if you've downloaded mochiweb) can be used directly from the Erlang shell as follows:

erl -pa path/to/mochiweb/ebin
...
1> mochijson2:decode(<<"[1,2,3]">>).
[1,2,3]
2> iolist_to_binary(mochijson2:encode([1,2,3])).
<<"[1,2,3]">>

There are some test cases at the bottom of mochiweb/src/mochijson2.erl that might also be helpful in understanding the mapping between JSON terms and Erlang terms.

Jiva answered 16/6, 2009 at 11:27 Comment(0)
L
8

Yeah, I had to spend a bunch of time in the source code to figure out what was going on. Actually, that describes a lot of my experience with Erlang. This has gotten me by, generating the JSON I need. Here's a quick example.

ERL  :: {struct, [{strKey, <<"strVal">>}, {intKey, 10}, {arrayKey, [1, 2, 3]}]}
JSON :: {strKey:"strVal", intKey:10, arrayKey:[1, 2, 3]}

So in that example you can see how to make objects (which mochijson2 wants you to call structs), strings, integers and arrays. Good luck!

Lilialiliaceous answered 17/6, 2009 at 6:8 Comment(0)
L
4

I suggest reading/watching/downloading Start Developing Web Applications on Erlang

Lida answered 16/6, 2009 at 8:22 Comment(0)
C
1

Here are the equivalent erlang commands in addition to @rik.the.vik's comment:

erl -pa path/to/mochiweb/ebin
...
iolist_to_binary(mochijson2:encode({struct, [{strKey, <<"strVal">>}, {intKey, 10}, {arrayKey, [1, 2, 3]}]})).
mochijson2:decode(<<"{\"strKey\":\"strVal\", \"intKey\":10, \"arrayKey\":[1, 2, 3]}">>).
Calx answered 27/8, 2013 at 22:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.