Skip to content

Instantly share code, notes, and snippets.

@lpgauth
Last active December 26, 2021 13:54
Show Gist options
  • Save lpgauth/78f81fabbea0f959759d to your computer and use it in GitHub Desktop.
Save lpgauth/78f81fabbea0f959759d to your computer and use it in GitHub Desktop.
generating json (erlang)
-module(json_fun).
-export([
test/0
]).
-record(my_api, {
name,
age,
cars
}).
-record(car, {
name,
year
}).
%% public
test() ->
my_api_json(#my_api {
name = <<"LP">>,
age = 28,
cars = [
#car {
name = <<"Toyota">>,
year = <<"2014">>
},
#car {
name = <<"Lexus">>
}
]
}).
%% private
my_api_json(#my_api {} = MyApi) ->
jiffy:encode({zip(record_info(fields, my_api), tl(tuple_to_list(MyApi)))}).
car_json(#car {} = Car) ->
jiffy:encode({zip(record_info(fields, car), tl(tuple_to_list(Car)))}).
zip([], []) -> [];
zip([_ | T], [undefined | T2]) -> zip(T, T2);
zip([cars | T], [Cars | T2]) ->
[{cars, [car_json(Car) || Car <- Cars]} | zip(T, T2)];
zip([H | T], [H2 | T2]) ->
[{atom_to_binary(H, utf8), H2} | zip(T, T2)].
@lpgauth
Copy link
Author

lpgauth commented Nov 13, 2014

json_fun:test().
<<"{"name":"LP","age":28,"cars":["{\"name\":\"Toyota\",\"year\":\"2014\"}","{\"name\":\"Lexus\"}"]}">>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment