Skip to content

Decoding

Eric Pailleau edited this page Aug 12, 2017 · 28 revisions

Decoding

Exported functions

  • jason:decode/1
  • jason:decode/2
  • jason:decode_file/1
  • jason:decode_file/2

Options

Arity 2 functions accept a property list of {key, Value} tuples.

key value Comment
mode struct, proplist, map, record struct default.

Return value

By default, returns Erlang term or exception on error.

Using option {return, tuple} let return {ok, Term} or {error, {Line, Reason}}.

1> jason:decode('{"ab": "cd"}').    
[{<<"ab">>,<<"cd">>}]
2> jason:decode('{"ab": "cd"}', [{return, tuple}]).
{ok,[{<<"ab">>,<<"cd">>}]}
1> jason:decode('{"ab": "cd"').
** exception throw: {1,"syntax error before end"}
     in function  jason:decode/2 (src/jason.erl, line 211)
2> jason:decode('{"ab": "cd"', [{return, tuple}]).
{error,{1,"syntax error before end"}}

Data Input

jason:decode/x functions can accept binary, string and even atom data to decode.

Tip : it is worth noting that using atom in Erlang shell is easier than using string or binary for character escaping . For your mental health, use atoms in the shell for short JSON statements !

1> jason:decode('["a","b\\""]').              % Atom (but limited to 255 characters !)
{ok,[<<"a">>,<<"b\"">>]}
2> jason:decode(<<"[\"a\",\"b\\\"\"]">>).     % Binary
{ok,[<<"a">>,<<"b\"">>]}
3> jason:decode("[\"a\",\"b\\\"\"]").         % String
{ok,[<<"a">>,<<"b\"">>]}

Clone this wiki locally