Last active
December 26, 2021 13:54
-
-
Save lpgauth/78f81fabbea0f959759d to your computer and use it in GitHub Desktop.
generating json (erlang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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)]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
json_fun:test().
<<"{"name":"LP","age":28,"cars":["{\"name\":\"Toyota\",\"year\":\"2014\"}","{\"name\":\"Lexus\"}"]}">>