2016-08-02 101 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"}]