-
Notifications
You must be signed in to change notification settings - Fork 4
Decoding
Eric Pailleau edited this page Jan 6, 2018
·
28 revisions
jason:decode/1jason:decode/2jason:decode_file/1jason:decode_file/2
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. |
records |
[{atom(), [atom(), ...]},...] |
[{RecName, RecFields}, ...] |
(List of) Record definitions |
records |
[atom(), ...] |
Module name(s) where record(s) declared | Extract record info from (list of) module (slower) |
See also Options.
When using records, argonaut modules are not created when a match is found between declaration and data.
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\"">>]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"}}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}