sile / jsone

Erlang JSON library
MIT License
291 stars 72 forks source link

Convert map to json and back #30

Closed chbest-btc closed 6 years ago

chbest-btc commented 6 years ago

Hey guys, thx for providing this great lib. :-)

I have a question for the usage of your lib. I try to convert a map to json and back. According to the Data Mapping provided in your doc, this is the case:

{key => val} -> {"key":"val"} -> #{<<"key">> => <<"val">>} % object_format=map

This is what I am doing: 1> Json = jsone:encode(#{key => val}). <<"{\"key\":\"val\"}">> 2> Map = jsone:decode(Json). {[{<<"key">>,<<"val">>}]} 3> maps:find(key, Map).

This is my result: ** exception error: {badmap,{[{<<"key">>,<<"val">>}]}}

And this is what I expect as result: val

Can anybody provide me help on how to map a map to a json and back?

pichi commented 6 years ago

Try use

Map = jsone:decode(Json, [{object_format, map}]).

or may be

Map = jsone:decode(Json, [{object_format, map}, {keys, attempt_atom}]).

Look at doc/jsone.md#type-decode_option for more options.

chbest-btc commented 6 years ago

That does work:

2> Map = jsone:decode(Json, [{object_format, map}]).
#{<<"key">> => <<"val">>}
3> maps:find(<<"key">>, Map).
{ok,<<"val">>}

Thanks. :-)

sile commented 6 years ago

Thanks! > @pichi