我有一段JSON字符串,我想在Erlang中解析它。它看起来像:
({ id1 : ["str1", "str2", "str3"], id2 : ["str4", "str5"]})
我查看了mochijson2和其他一些JSON解析器,但我真的无法弄清楚如何做到这一点。任何帮助非常感谢!
答案 0 :(得分:14)
我曾使用erlang-json-eep-parser,并对您的数据进行了尝试。
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
是的,它不喜欢括号。
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
它不喜欢不带引号的键:
18> json_eep:json_to_term("{ \"id1\" : [\"str1\", \"str2\", \"str3\"], \"id2\" : [\"str4\", \"str5\"]}").
{[{<<"id1">>,[<<"str1">>,<<"str2">>,<<"str3">>]},
{<<"id2">>,[<<"str4">>,<<"str5">>]}]}
看起来更好。
因此,您的数据似乎几乎 JSON,至少就此解析器而言。
答案 1 :(得分:2)
您可以在JSONLint验证器上处理您的JSON:http://www.jsonlint.com/
答案 2 :(得分:0)
你看过http://www.json.org/吗?
或从这里下载“json4erlang”:json-and-json-rpc-for-erlang
答案 3 :(得分:0)
您的输入不是JSON - 需要引用密钥,如下所示:
{ "id1" : ["str1", "str2", "str3"], "id2" : ["str4", "str5"]}
用于操作JSON的优秀Erlang库是jsx
答案 4 :(得分:0)
根据https://www.ietf.org/rfc/rfc4627.txt,您的JSON密钥无效。一旦你纠正它,Erlang有很多JSON库,我最喜欢的是JSX(https://github.com/talentdeficit/jsx/):
MyJSON = { "id1" : ["str1", "str2", "str3"], "id2" : ["str4", "str5"]},
jsx:decode(MyJSON, [return_maps]).
它将返回一个Erlang地图数据结构,可以根据您的需要进行操作http://learnyousomeerlang.com/maps