Skip to content

Encoding

Eric Pailleau edited this page Sep 1, 2018 · 25 revisions

Encoding

Exported functions

  • jason:encode/1
jason:encode(Term) -> string() | no_return()
  • jason:encode/2
jason:encode(Term, Options) -> list() | no_return() | {ok, list()} | {error, Reason}
    Reason = {'invalid_term', Term, Depth} | {unable_to_encode, Term, Depth}
  • jason:encode_file/2
jason:encode_file(Term, TargetFile) -> ok | {error, Reason}
    Reason = posix() | badarg | terminated | system_limit
  • jason:encode_file/3
jason:encode_file(Term, TargetFile, Options) -> ok | {error, Reason}
    Reason = posix() | badarg | terminated | system_limit

Options

Arity 2/3 functions accept a property list of {key, Value} tuples as last argument.

Key Value Type Value Comment
mode atom() struct, proplist, map, record struct default.
return atom() tuple Return mode.
indent atom() true, false false (compact) default.
records {atom(), [atom(), ...]} [{RecName, RecFields}, ...] List of Record definitions
records atom() [ModName, ...] Extract record info from module(s) (slower)

Data input

Any Erlang term that can be translated to JSON, excluding :

  • tuple with more than two elements, if no records declared.
  • tuple with a single element

Example :

1> jason:encode([{a,b}]). % Tuple with 2 elements is ok
"{\"a\": \"b\"}"
2> catch  jason:encode([{a, "b", "c"}]).  % Tuple with 3 elements is an error if no records declared
{unable_to_encode,a,1}
3> rd(a, {b, c}).    % Declare record in shell
4> A = jason:encode({a, "b", "c"}, [{records, [{a, [b,c]}]}]).  % Tuple with 3 elements with record declaration        
"{\"b\": \"b\",\"c\": \"c\"}"
5> jason:decode(A, [{mode, record}, {records, [{a, [b,c]}]}]). % Create back a record
#a{b = "b",c = "c"}
6> B = jason:decode(A, [{mode,record}]).   % Create ad-hoc (anonymous) record
{'86762006',"b","c"}
7> '86762006':b(B). % Use argonaut module to handle it
"b"
8> C = "{\"b\": 1.0, \"c\": \"test\"}".
"{\"b\": 1.0, \"c\": \"test\"}"
9> jason:decode(C, [{mode, record}, {aliases, [{a, [b,c]}]}]).
{a,1.0,"test"}
10> a:def().
"-record(a, {b  = 0.0  :: float(), c  = []  :: list()})."

Return value

% Success
1> jason:encode([1,2,3,a]).                   
"[1,2,3,\"a\"]"
2> jason:encode([1,2,3,a], [{return, tuple}]).
{ok, "[1,2,3,\"a\"]"}
% Error
1> catch jason:encode([1,2,3,{a}]).                   
{invalid_term,{a},1}
2> jason:encode([1,2,3,{a}], [{return, tuple}]).
{error, {invalid_term,{a},1}}
Clone this wiki locally