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
([email protected])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
"
([email protected])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
([email protected])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:
jiffy
is consistent so it will also decode JSON strings as Erlang binaries, which you need to take into account when usingjiffy:decode/1
.