2009-07-01 18 views
14

Ho un pezzo di stringa JSON, che voglio analizzare in Erlang. Sembra che:Parsing JSON in Erlang

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

ho guardato mochijson2, e un paio di altri parser JSON, ma davvero non riusciva a capire come farlo. Qualsiasi aiuto molto apprezzato!

+9

Ecco non vero JSON. Le chiavi devono essere citate e non ci dovrebbero essere parentesi intorno ad esso. – cdmckay

risposta

14

una volta ho usato il erlang-json-eep-parser, e l'ho provato sui dati.

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 

Giusto, non le piacciono le parentesi.

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 

E non come i tasti non quotate:

18> json_eep:json_to_term("{ \"id1\" : [\"str1\", \"str2\", \"str3\"], \"id2\" : [\"str4\", \"str5\"]}"). 
{[{<<"id1">>,[<<"str1">>,<<"str2">>,<<"str3">>]}, 
    {<<"id2">>,[<<"str4">>,<<"str5">>]}]} 

Questo sembra migliore.

Quindi sembra che i tuoi dati siano quasi JSON, almeno per quanto riguarda questo parser.

0

Hai guardato http://www.json.org/?

o scaricare "json4erlang" da qui: json-and-json-rpc-for-erlang

+0

Spiacente, vedo che erlang-json-parser è "Servizio temporaneamente non disponibile" – Blauohr

+0

Sì, ho visto l'implementazione di RFC4627, ma quando passo la stringa sopra come input alla funzione decode(), ricevo un errore "badarg". .. – thomas55

0

Il vostro contributo non è abbastanza JSON - le chiavi devono essere citato, in questo modo:

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

una buona biblioteca Erlang per manipolare JSON è jsx

0

Le tue chiavi JSON non sono valide in base a https://www.ietf.org/rfc/rfc4627.txt. Una volta che si correggerlo, ci sono un sacco di librerie JSON per Erlang, il mio preferito è JSX (https://github.com/talentdeficit/jsx/):

MyJSON = { "id1" : ["str1", "str2", "str3"], "id2" : ["str4", "str5"]}, 
jsx:decode(MyJSON, [return_maps]). 

e restituirà una struttura di dati mappa Erlang che può essere manipolato alle vostre esigenze http://learnyousomeerlang.com/maps