[英]Encoding Erlang Maps as JSON with Strings for parsing by Javascript?
I'm trying to take an Erlang map like我正在尝试使用 Erlang 地图,例如
#{"breakfast" => "leftovers"}
and encode as a JSON map.并编码为 JSON 映射。
I tried converting a list with jiffy for example例如,我尝试使用 jiffy 转换列表
(tunnel@127.0.0.1)27> binary_to_list(jiffy:encode(["alpha", "beta"] )).
"[[97,108,112,104,97],[98,101,116,97]]"
but I am unsure how to convert that to a JSON object.但我不确定如何将其转换为 JSON 对象。
When I try to convert a map I get " invalid_member_key
"当我尝试转换地图时,我得到“ invalid_member_key
”
(tunnel@127.0.0.1)28> jiffy:encode(#{"breakfast" => "egg sandwhich"}).
** exception throw: {error,{invalid_object_member_key,"breakfast"}}
in function jiffy:encode/2 (src/jiffy.erl, line 97)
I tried the pretty formatter for the list and I get newlines我为列表尝试了漂亮的格式化程序,我得到了换行符
(tunnel@127.0.0.1)31> binary_to_list(jiffy:encode(["alpha", "beta"], [pretty] )).
"[\n [\n 97,\n 108,\n 112,\n 104,\n 97\n ],\n [\n 98,\n 101,\n 116,\n 97\n ]\n]"
Why isn't this working?为什么这不起作用? a json_object is一个 json_object 是
-type json_object() :: {[{json_string(),json_value()}]}
| #{json_string() => json_value()}.
so I'm expecting the map conversion to work.所以我期待地图转换工作。 I've tried searching and found examples on reading JSON but not a working example of converting Erlang into readable JSON.我尝试搜索并找到了有关读取 JSON 的示例,但没有找到将 Erlang 转换为可读 JSON 的工作示例。
The problem is that in Erlang the string "hello"
is just a list of integer.问题是在 Erlang 中,字符串"hello"
只是一个整数列表。 The libraries that encode Erlang maps into JSON interpret strings as JSON lists, that is why you get a list of integers in the output.将 Erlang 映射到 JSON 的库将字符串解释为 JSON 列表,这就是为什么您会在输出中获得整数列表的原因。
In order to get JSON strings you need to use Erlang binaries as the values in your maps:为了获得 JSON 字符串,您需要使用 Erlang 二进制文件作为映射中的值:
Food = #{<<"breakfast">> => <<"leftovers">>},
jiffy:encode(Food).
%%= <<"{ \"breakfast\" : \"leftovers\" }">>
jiffy
is consistent so it will also decode JSON strings as Erlang binaries, which you need to take into account when using jiffy:decode/1
. jiffy
是一致的,因此它也会将 JSON 字符串解码为 Erlang 二进制文件,在使用jiffy:decode/1
时需要考虑到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.