JSON and term formats

A value that leaves a program needs a format. Inside an Erlang cluster the native external term format is exact and cheap. At the edge, another language reads JSON. On a channel that carries text only, both travel as Base64. This lesson writes each one and names the mistake each format has.

Terms everywhere

term_to_binary/1 turns any term into the external term format, and binary_to_term/1 turns the bytes back into the value. The first byte is 131, the format tag, and the rest describes the term exactly: tuples, lists, atoms, integers, binaries and maps all round-trip:

erl

1> term_to_binary({ok, [1, 2]}). <<131,104,2,119,2,111,107,107,0,2,1,2>> 2> binary_to_term(term_to_binary({ok, [1, 2]})). {ok,[1,2]} 3> byte_size(term_to_binary({ok, [1, 2]})). 12

The format is versioned and stable enough to store in a file or send to another node of the same release. It is not a format for another language: a JSON reader cannot read it, and its atoms are the atoms of the runtime, which is the subject of the next section.

JSON in OTP 27

Since OTP 27 the standard library ships the json module, so a fresh install encodes and decodes without a dependency. json:encode/1 answers iodata, not a binary, and json:decode/1 answers maps with binary keys. A charlist is a list, so JSON encodes it as an array of code points; text must be a binary:

wire.erl

-module(wire). -export([main/0]). main() -> Encoded = iolist_to_binary(json:encode(#{name => <<"Ada">>})), io:format("~s~n", [Encoded]), io:format("~p~n", [json:decode(Encoded)]), io:format("~s~n", [iolist_to_binary(json:encode(#{name => "Ada"}))]).

erlc wire.erl

erl -noshell -eval 'wire:main(), halt().'

{"name":"Ada"} #{<<"name">> => <<"Ada">>} {"name":[65,100,97]}

The third line is the trap: "Ada" is a list of integers, and the encoder is right to write an array. Write <<"Ada">> for a JSON string. A decoded object is a map with binary keys, so maps:get(<<"name">>, Map) reads it and an atom key does not.

Untrusted bytes

binary_to_term/1 creates the atoms the bytes name, and the atom table is never garbage collected. A message from outside that names a million new atoms can exhaust the node, and an atom from an old term can even name a module the program did not intend to use. The safe option refuses an atom that does not already exist:

safe.erl

-module(safe). -export([main/0]). main() -> Bin = <<131, 100, 0, 3, "xyz">>, Result = try binary_to_term(Bin, [safe]) of Term -> {ok, Term} catch error:badarg -> rejected end, io:format("~p~n", [Result]), io:format("~p~n", [binary_to_term(Bin)]).

erlc safe.erl

erl -noshell -eval 'safe:main(), halt().'

rejected xyz

The first call refuses the new atom and the second creates it, which is the whole difference. Use [safe] on every binary that crossed a process boundary you do not control, or send JSON instead and pay the conversion. A config file is a third form: file:consult/1 reads Erlang terms from a file that the operator wrote, not from the wire, and the term formats lesson shows it.

Base64

base64:encode/1 turns a binary into ASCII text and base64:decode/1 turns it back. It is the way to carry bytes over a header, a query string or a log line that cannot hold them raw. A term travels as term_to_binary and then Base64:

pack.erl

-module(pack). -export([main/0]). main() -> io:format("~s~n", [base64:encode(<<"hello">>)]), Packed = base64:encode(term_to_binary({ok, [1, 2]})), io:format("~p~n", [binary_to_term(base64:decode(Packed))]).

erlc pack.erl

erl -noshell -eval 'pack:main(), halt().'

aGVsbG8= {ok,[1,2]}

Base64 makes a value larger by about a third, and it hides the structure from a reader, so it is a transport, not a storage format. The padding with = is part of the encoding; a decoder rejects a string whose length was cut.

Which format

Match the format to the reader. Inside a cluster of Erlang nodes, use term_to_binary with [safe] on input; both ends are Erlang and the native format is exact. Across languages, use JSON and accept that keys are binaries and numbers lose their Erlang types. On a text-only channel, Base64 the result of either. A file that a human edits is none of these: it is a config file, and file:consult/1 reads Erlang terms from it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does term_to_binary({ok, [1, 2]}) start with?

    Answer

    <<131>>

    The first byte 131 is the external term format tag that binary_to_term expects.

  2. What does binary_to_term(term_to_binary(Term)) answer?

    Answer

    The original term

    The pair round-trips every term exactly, including nested lists and tuples.

  3. What does json:encode/1 answer?

    Answer

    Iodata

    It answers iodata, so the lesson wraps it in iolist_to_binary/1 to get a binary.

  4. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~s~n", [iolist_to_binary(json:encode(#{name => <<"Ada">>}))]).

    Answer

    {"name":"Ada"}

    The value is a binary, so JSON writes a string, and the encoded iodata is turned into a binary.

  5. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~s~n", [iolist_to_binary(json:encode(#{name => "Ada"}))]).

    Answer

    {"name":[65,100,97]}

    A charlist is a list, so the encoder writes an array of its three code points.

  6. What does this module print? -module(q3). -export([main/0]). main() -> Bin = <<131, 100, 0, 3, "xyz">>, io:format("~p~n", [try binary_to_term(Bin, [safe]) of Term -> {ok, Term} catch error:badarg -> rejected end]).

    Answer

    rejected

    The safe option refuses an atom that the node does not already have, so the call raises badarg.

  7. What does this module print? -module(q4). -export([main/0]). main() -> io:format("~s~n", [base64:encode(<<"hi">>)]).

    Answer

    aGk=

    Two bytes encode to four Base64 characters, and = pads the last group.

  8. What kind of keys does json:decode/1 produce?

    Answer

    Binary keys

    Decoded objects are maps with binary keys, as in #{<<"name">> => <<"Ada">>}.

  9. Why use [safe] with binary_to_term/2 on input from outside?

    Answer

    It refuses atoms that do not already exist

    The atom table never shrinks, so an untrusted binary must not be allowed to create atoms.

  10. Which format belongs inside your own Erlang cluster?

    Answer

    term_to_binary

    Both ends are Erlang, so the native term format is exact and cheap; JSON belongs at the edges.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev