简体   繁体   中英

Encoding Erlang Maps as JSON with Strings for parsing by Javascript?

I'm trying to take an Erlang map like

#{"breakfast" => "leftovers"}

and encode as a JSON map.

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]]"

but I am unsure how to convert that to a JSON object.

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]"

Why isn't this working? a json_object is

-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.

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.

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 is consistent so it will also decode JSON strings as Erlang binaries, which you need to take into account when using jiffy:decode/1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM