Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON in Erlang

Tags:

json

erlang

I have a piece of JSON string, which I want to parse in Erlang. It looks like:

({ id1 : ["str1", "str2", "str3"], id2 : ["str4", "str5"]})

I looked at mochijson2, and a couple of other JSON parsers, but I really could not figure out how to do it. Any help greatly appreciated!

like image 612
thomas55 Avatar asked Jul 01 '09 14:07

thomas55


3 Answers

I once used the erlang-json-eep-parser, and tried it on your data.

7> json_eep:json_to_term("({ id1 : [\"str1\", \"str2\", \"str3\"], id2 : [\"str4\", \"str5\"]})").
** exception error: no match of right hand side value 
                    {error,{1,json_lex2,{illegal,"("}},1}
     in function  json_eep:json_to_term/1

Right, it doesn't like the parentheses.

8> json_eep:json_to_term("{ id1 : [\"str1\", \"str2\", \"str3\"], id2 : [\"str4\", \"str5\"]}").
** exception error: no match of right hand side value 
                    {error,{1,json_lex2,{illegal,"i"}},1}
     in function  json_eep:json_to_term/1

And it doesn't like the unquoted keys:

18> json_eep:json_to_term("{ \"id1\" : [\"str1\", \"str2\", \"str3\"], \"id2\" : [\"str4\", \"str5\"]}").
{[{<<"id1">>,[<<"str1">>,<<"str2">>,<<"str3">>]},
  {<<"id2">>,[<<"str4">>,<<"str5">>]}]}

That looks better.

So it seems that your data is almost JSON, at least as far as this parser is concerned.

like image 175
legoscia Avatar answered Oct 16 '22 03:10

legoscia


you can work on your JSON at the JSONLint validator: http://www.jsonlint.com/

like image 2
Paul B. Hartzog Avatar answered Oct 16 '22 05:10

Paul B. Hartzog


Your input is not quite JSON -- the keys need to be quoted, like this:

{ "id1" : ["str1", "str2", "str3"], "id2" : ["str4", "str5"]}

A good Erlang library for manipulating JSON is jsx

like image 1
btk Avatar answered Oct 16 '22 04:10

btk