Parsing JSON in Erlang

前端 未结 5 2007
一整个雨季
一整个雨季 2021-02-05 15:44

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

({ id1 : [\"str1\", \"str2\", \"str3\"], id2 : [\"str4\", \"str5\"]})
相关标签:
5条回答
  • 2021-02-05 15:54

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

    0 讨论(0)
  • 2021-02-05 15:59

    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

    0 讨论(0)
  • 2021-02-05 15:59

    Your JSON keys are not valid according to https://www.ietf.org/rfc/rfc4627.txt. Once you correct it, there are plenty of JSON libraries for Erlang, my favorite is 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

    0 讨论(0)
  • 2021-02-05 16:00

    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.

    0 讨论(0)
  • 2021-02-05 16:08

    Have you looked at http://www.json.org/ ?

    or download "json4erlang" from here: json-and-json-rpc-for-erlang

    0 讨论(0)
提交回复
热议问题