2016-08-02 11 views
0

JSXを使用して、タプルのリストをJSONオブジェクトに変換しようとしています。Mnesiaのクエリ結果を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

jsxがJSONに正しくエンコードできる用語にレコードを変換する必要があります。 playerレコードのリストのJSON内のオブジェクトの配列が必要な場合は、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"}] 
関連する問題