2016-08-02 124 views
0

我正在尝试使用JSX将元组列表转换为JSON对象。如何将Mnesia查询结果转换为JSON'able列表?

列表项是基于记录定义:

-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

您必须将记录转换为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"}] 
相关问题