我正在尝试使用JSX将元组列表转换为JSON对象。
列表项基于记录定义:
-record(player, {index, name, description}).
看起来像这样:
[
{player,1,"John Doe","Hey there"},
{player,2,"Max Payne","I am here"}
]
查询功能如下所示:
select_all() ->
SelectAllFunction =
fun() ->
qlc:eval(qlc:q(
[Player ||
Player <- mnesia:table(player)
]
))
end,
mnesia:transaction(SelectAllFunction).
什么是使其可转换为JSON的正确方法,因为我知道我使用了记录的模式并知道元组的结构?
答案 0 :(得分:0)
您必须将记录转换为jsx
可以正确编码为JSON的术语。假设您需要JSON中的一组对象作为player
记录列表,您必须将每个player
转换为映射或元组列表。您还必须将字符串转换为二进制文件,否则jsx
会将其编码为整数列表。这是一些示例代码:
-record(player, {index, name, description}).
player_to_json_encodable(#player{index = Index, name = Name, description = Description}) ->
[{index, Index}, {name, list_to_binary(Name)}, {description, list_to_binary(Description)}].
go() ->
Players = [
{player, 1, "John Doe", "Hey there"},
% the following is just some sugar for a tuple like above
#player{index = 2, name = "Max Payne", description = "I am here"}
],
JSON = jsx:encode(lists:map(fun player_to_json_encodable/1, Players)),
io:format("~s~n", [JSON]).
测试:
1> r:go().
[{"index":1,"name":"John Doe","description":"Hey there"},{"index":2,"name":"Max Payne","description":"I am here"}]