How to read a key value after decoding json in erlang

2.5k Views Asked by At

Here is a short query

In Erlang I parsed json using

Ccode = jiffy:decode(<<"{\"foo\": \"bar\"}">>).

it returns

{[{<<"foo">>,<<"bar">>}]}

Now target is to get value of 'foo' and it should return 'bar'

any help is appreciated.

3

There are 3 best solutions below

1
On BEST ANSWER

You can extract a list of attributes of the JSON object using pattern matching and then find a value by a key in the resulting list:

{Attrs} = jiffy:decode(<<"{\"foo\": \"bar\"}">>),
FooValue = proplists:get_value(<<"foo">>, Attrs).
0
On

You can try ej module:

The ej module makes it easier to work with Erlang terms representing JSON in the format returned by jiffy, mochijson2, or ejson. You can use ej:get/2 to walk an object and return a particular value, ej:set/3 to update a value within an object, or ej:delete/2 to remove a value from an object.

2
On

I find jsx easy to use:

Eshell V6.2  (abort with ^G)
1> Data = jsx:decode(<<"{\"foo\": \"bar\"}">>).
[{<<"foo">>,<<"bar">>}]
2> proplists:get_value(<<"foo">>, Data).
<<"bar">>

You can even parse it into Maps.

3> Map = jsx:decode(<<"{\"foo\": \"bar\"}">>, [return_maps]).
#{<<"foo">> => <<"bar">>}
4> maps:get(<<"foo">>, Map).
<<"bar">>