Json in Erlang
-module(json_example).
-export([main/0]).
-record(response1, {page, fruits}).
-record(response2, {page, fruits}).
main() ->
% Encoding basic data types to JSON strings
BolB = jsx:encode(true),
io:format("~s~n", [BolB]),
IntB = jsx:encode(1),
io:format("~s~n", [IntB]),
FltB = jsx:encode(2.34),
io:format("~s~n", [FltB]),
StrB = jsx:encode(<<"gopher">>),
io:format("~s~n", [StrB]),
% Encoding slices and maps
SlcD = [<<"apple">>, <<"peach">>, <<"pear">>],
SlcB = jsx:encode(SlcD),
io:format("~s~n", [SlcB]),
MapD = #{<<"apple">> => 5, <<"lettuce">> => 7},
MapB = jsx:encode(MapD),
io:format("~s~n", [MapB]),
% Encoding custom data types
Res1D = #response1{page = 1, fruits = [<<"apple">>, <<"peach">>, <<"pear">>]},
Res1B = jsx:encode(Res1D),
io:format("~s~n", [Res1B]),
Res2D = #response2{page = 1, fruits = [<<"apple">>, <<"peach">>, <<"pear">>]},
Res2B = jsx:encode(Res2D),
io:format("~s~n", [Res2B]),
% Decoding JSON data
Byt = <<"{\"num\":6.13,\"strs\":[\"a\",\"b\"]}">>,
{ok, Dat} = jsx:decode(Byt, [return_maps]),
io:format("~p~n", [Dat]),
Num = maps:get(<<"num">>, Dat),
io:format("~p~n", [Num]),
Strs = maps:get(<<"strs">>, Dat),
Str1 = lists:nth(1, Strs),
io:format("~s~n", [Str1]),
% Decoding JSON into custom data types
Str = <<"{\"page\": 1, \"fruits\": [\"apple\", \"peach\"]}">>,
{ok, Res} = jsx:decode(Str, [return_maps]),
io:format("~p~n", [Res]),
io:format("~s~n", [lists:nth(1, maps:get(<<"fruits">>, Res))]),
% Encoding directly to standard output
D = #{<<"apple">> => 5, <<"lettuce">> => 7},
io:format("~s~n", [jsx:encode(D)]).
This Erlang code demonstrates JSON encoding and decoding using the jsx
library, which is commonly used for JSON operations in Erlang. Here’s a breakdown of the translation:
We define records
response1
andresponse2
to represent custom data types.The
main/0
function contains all the example operations.For encoding, we use
jsx:encode/1
to convert Erlang terms to JSON strings.For decoding, we use
jsx:decode/2
with thereturn_maps
option to convert JSON to Erlang maps.We use Erlang’s binary syntax (`«»``) for JSON strings, as it’s more efficient than regular strings.
Map syntax (
#{key => value}
) is used instead of Go’s map syntax.List comprehensions and
lists
module functions are used for operations on lists (Erlang’s equivalent to slices).io:format/2
is used for printing to standard output.
To run this program, you would need to:
- Install Erlang and the
jsx
library. - Save the code in a file named
json_example.erl
. - Compile the file using
erlc json_example.erl
. - Run the program using
erl -noshell -s json_example main -s init stop
.
Note that Erlang doesn’t have a direct equivalent to Go’s struct tags for JSON field naming. In practice, you might need to write custom encoding/decoding functions for more complex scenarios.