[英]Parsing JSON in Erlang
I have a piece of JSON string, which I want to parse in Erlang. 我有一段JSON字符串,我想在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. 我查看了mochijson2和其他几个JSON解析器,但我真的无法弄清楚如何做到这一点。 Any help greatly appreciated! 任何帮助非常感谢!
I once used the erlang-json-eep-parser , and tried it on your data. 我曾经使用过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
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. 所以看起来你的数据几乎就是JSON,至少就这个解析器而言。
您可以在JSONLint验证器上使用JSON: http : //www.jsonlint.com/
Have you looked at http://www.json.org/ ? 你看过http://www.json.org/吗?
or download "json4erlang" from here: json-and-json-rpc-for-erlang 或者从这里下载“json4erlang”: json-and-json-rpc-for-erlang
Your JSON keys are not valid according to https://www.ietf.org/rfc/rfc4627.txt . 根据https://www.ietf.org/rfc/rfc4627.txt,您的JSON密钥无效。 Once you correct it, there are plenty of JSON libraries for Erlang, my favorite is JSX( https://github.com/talentdeficit/jsx/ ): 一旦你纠正它,Erlang有很多JSON库,我最喜欢的是JSX( https://github.com/talentdeficit/jsx/ ):
MyJSON = { "id1" : ["str1", "str2", "str3"], "id2" : ["str4", "str5"]},
jsx:decode(MyJSON, [return_maps]).
And it will return an Erlang map data structure that can be manipulated to your needs http://learnyousomeerlang.com/maps 它将返回一个Erlang地图数据结构,可以根据您的需要进行操作http://learnyousomeerlang.com/maps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.