JSON and term formats
| Terms everywhere | |
| JSON libraries | |
| Base64 and friends | |
| Which format |
Terms everywhere
Any Erlang term can turn into a binary and back. term_to_binary and binary_to_term are the pair every Erlang developer knows.
The format is stable across OTP releases within reason, and it round-trips every value exactly.
1> term_to_binary({ok, [1, 2]}).
<<131,104,2,100,0,2,111,107,108,0,0,0,2,1,2>>
2> binary_to_term(term_to_binary({ok, [1, 2]})).
{ok,[1,2]}
JSON libraries
Erlang ships no JSON in the core, so projects add jiffy or jsx through rebar3. Both encode maps and lists and decode JSON into maps.
The decode answer is a map, so the maps tools of lesson 14 take over from there.
1> jiffy:encode(#{name => "Ada"}).
<<"{\"name\":\"Ada\"}">>
2> jiffy:decode("{\"name\":\"Ada\"}", [return_maps]).
#{name => "Ada"}
Base64 and friends
The base64 module encodes binaries to ASCII text and back. It is the standard way to carry binary payloads over text-only channels.
The erlang module also packs and unpacks smaller bases when the payload is tiny.
1> base64:encode("hello").
<<"aGVsbG8=">>
2> base64:decode("aGVsbG8=").
<<"hello">>
Which format
Use term_to_binary inside your own cluster, JSON at the edges with other languages, and Base64 when text channels force it.
The rule of thumb: match the format to the reader, never to the writer.
% inside the cluster: term_to_binary
% across languages: jiffy:encode
% text-only wire: base64:encode
Next: Processes and message passing
Article author: Arthur Isaev