gpt4 book ai didi

Erlang 元组列表 jsx :encode error

转载 作者:行者123 更新时间:2023-12-02 00:52:39 26 4
gpt4 key购买 nike

我想用 jsx:encode 创建一个 json 格式的元组列表,它返回错误:

    io:format("Mylist After reverse ==========: ~n~p~n",[Mylist]),

FinalReading = lists:map(
fun(X) ->
jsx:encode([X])
end, Mylist),

Mylist打印如下:

    [{{<<"name">>,<<"Batman">>},{<<"steps">>,1033},{<<"distance">>,830}},
{{<<"name">>,<<"Superman">>},{<<"steps">>,641},{<<"distance">>,520}}]

我收到这个错误:

    09:49:24.048 [error] ** Boss Service Handler myproj_priv_mylib_websocket terminating in handle_incoming/4
for the reason error:badarg
ServiceUrl: "/websocket/mylib"
WebSocketId: <0.336.0>
SessionId : <<"a4f60118091309990af7c89c9a1acb49ee3bb08d">>
Message : <<"admin@mydomain.com:z3CMLU9jDTYdiAacNiJrMIkdp4lTf6sb">>
State : []
** Stacktrace: [{jsx_parser,value,4,[{file,"src/jsx_parser.erl"},{line,125}]},{lists,map,2,[{file,"lists.erl"},{line,1237}]},{myproj_priv_mylib_websocket,handle_incoming,5,[{file,"..."},{line,130}]},{boss_service_worker,handle_cast,2,[{file,"src/boss/boss_service_worker.erl"},{line,173}]},{gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,599}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,239}]}]

如果有人指出正确的代码就太好了。提前感谢大家。

最佳答案

您必须使用 erlang:tuple_to_list/1lists:map/2 将顶级元组转换为列表,以便 jsx 可以正确地将它们编码为 JSON 数组。

1> List = [{{<<"name">>,<<"Batman">>},{<<"steps">>,1033},{<<"distance">>,830}},
1> {{<<"name">>,<<"Superman">>},{<<"steps">>,641},{<<"distance">>,520}}].
[{{<<"name">>,<<"Batman">>},
{<<"steps">>,1033},
{<<"distance">>,830}},
{{<<"name">>,<<"Superman">>},
{<<"steps">>,641},
{<<"distance">>,520}}]
2> List2 = lists:map(fun erlang:tuple_to_list/1, List).
[[{<<"name">>,<<"Batman">>},
{<<"steps">>,1033},
{<<"distance">>,830}],
[{<<"name">>,<<"Superman">>},
{<<"steps">>,641},
{<<"distance">>,520}]]
3> io:format("~s~n", [jsx:encode(List2)]).
[{"name":"Batman","steps":1033,"distance":830},{"name":"Superman","steps":641,"distance":520}]

关于Erlang 元组列表 jsx :encode error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38487067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com