【问题标题】:Parsing JSON in Erlang在 Erlang 中解析 JSON
【发布时间】:2010-11-07 08:38:18
【问题描述】:

我有一段 JSON 字符串,我想在 Erlang 中解析它。它看起来像:

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

我查看了 mochijson2 和其他几个 JSON 解析器,但我真的不知道该怎么做。非常感谢任何帮助!

【问题讨论】:

  • 这不是真正的 JSON。键需要用引号括起来,并且不能用括号括起来。

标签: json erlang


【解决方案1】:

我曾经使用过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,至少就这个解析器而言。

【讨论】:

    【解决方案2】:

    您可以在 JSONLint 验证器上处理您的 JSON:http://www.jsonlint.com/

    【讨论】:

      【解决方案3】:

      您的输入并不完全是 JSON - 需要引用键,如下所示:

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

      一个很好的处理 JSON 的 Erlang 库是 jsx

      【讨论】:

        【解决方案4】:

        你看过http://www.json.org/吗?

        或从这里下载“json4erlang”:json-and-json-rpc-for-erlang

        【讨论】:

        • 对不起,我看到 erlang-json-parser 是“服务暂时不可用”
        • 是的,我看到了 RFC4627 实现,但是当我将上面的字符串作为输入传递给 decode() 函数时,我得到了一个“badarg”错误...
        【解决方案5】:

        根据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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-04
          • 2011-02-13
          • 1970-01-01
          相关资源
          最近更新 更多