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 type Value Comment
mode atom() struct, proplist, map, record Output mode. struct default.
return atom() tuple Return mode.
to list() Path to non existing or empty file Export Record definitions to file.

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 !)
[<<"a">>,<<"b\"">>]
2> jason:decode(<<"[\"a\",\"b\\\"\"]">>).     % Binary
[<<"a">>,<<"b\"">>]
3> jason:decode("[\"a\",\"b\\\"\"]").         % String
[<<"a">>,<<"b\"">>]

Return value

decode functions

By default, returns Erlang term on success, or throw {Line, Reason} exception on error.

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

% Success
1> jason:decode('{"ab": "cd"}').    
[{<<"ab">>,<<"cd">>}]
2> jason:decode('{"ab": "cd"}', [{return, tuple}]).
{ok,[{<<"ab">>,<<"cd">>}]}
% Error
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"}}

decode_file functions

Same than decode functions, but POSIX atom error returned instead {Line, Reason} on IO errors.

1> jason:decode_file("/tmp/notfound").         
** exception throw: enoent
     in function  jason:decode_file/2 (src/jason.erl, line 246)
 
2> jason:decode_file("/tmp/notfound", [{return, tuple}]).         
{error,enoent}

Clone this wiki locally