【问题标题】:How to convert Mnesia query results to a JSON'able list?如何将 Mnesia 查询结果转换为 JSON'able 列表?
【发布时间】:2016-08-02 16:12:31
【问题描述】:

我正在尝试使用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 的正确方法是什么?

【问题讨论】:

    标签: json erlang mnesia


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多