将Erlang Maps编码为JSON,并使用字符串进行解析? [英] Encoding Erlang Maps as JSON with Strings for parsing by Javascript?
问题描述
我正在尝试使用Erlang地图,如
I'm trying to take an Erlang map like
#{"breakfast" => "leftovers"}
并编码为JSON地图。
and encode as a JSON map.
我尝试用jiffy转换列表,例如
I tried converting a list with jiffy for example
(tunnel@127.0.0.1)27> binary_to_list(jiffy:encode(["alpha", "beta"] )).
"[[97,108,112,104,97],[98,101,116,97]]"
但是我不确定如何将其转换为JSON对象。
but I am unsure how to convert that to a JSON object.
当我尝试转换地图时,我会收到 invalid_member_key
When I try to convert a map I get "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]"
为什么这不工作?一个json_object是
Why isn't this working? a json_object is
-type json_object() :: {[{json_string(),json_value()}]}
| #{json_string() => json_value()}.
所以我期待地图转换工作。我已经尝试搜索并发现阅读JSON的例子,但不是将Erlang转换为可读JSON的工作示例。
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.
推荐答案
是在Erlang中,字符串hello
只是一个整数列表。编码Erlang的库映射到JSON将字符串解释为JSON列表,这就是为什么在输出中得到整数的列表。
The problem is that in Erlang the string "hello"
is just a list of integer. 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.
为了获得JSON字符串,您需要使用Erlang二进制文件作为地图中的值:
In order to get JSON strings you need to use Erlang binaries as the values in your maps:
Food = #{<<"breakfast">> => <<"leftovers">>},
jiffy:encode(Food).
%%= <<"{ \"breakfast\" : \"leftovers\" }">>
jiffy
是一致的,所以它也会解码JSON字符串作为Erlang二进制文件,在使用 jiffy:decode / 1
时需要考虑。
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
.
这篇关于将Erlang Maps编码为JSON,并使用字符串进行解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!