Parsing JSON in Erlang
15,593
Solution 1
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.
Solution 2
you can work on your JSON at the JSONLint validator: http://www.jsonlint.com/
Solution 3
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
Related videos on Youtube
Author by
thomas55
Updated on April 15, 2022Comments
-
thomas55 about 2 years
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!
-
cdmckay almost 15 yearsThat's not true JSON. The keys need to be quoted and there should be no brackets around it.
-
-
Blauohr almost 15 yearsSorry I see the erlang-json-parser is "Service Temporarily Unavailable"
-
thomas55 almost 15 yearsYes, I saw the RFC4627 implementation, but when I pass the above string as input to the decode() function, I am getting a "badarg" error...