如何将 Mnesia 查询结果转换为 JSON 可用列表?
How to convert Mnesia query results to a JSON'able list?
我正在尝试使用 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 的正确方法是什么?
您必须将记录转换为 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"}]
我正在尝试使用 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 的正确方法是什么?
您必须将记录转换为 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"}]