简体   繁体   English

在erlang中解码json后如何读取键值

[英]How to read a key value after decoding json in erlang

Here is a short query这是一个简短的查询

In Erlang I parsed json using在 Erlang 我解析 json 使用

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

it returns它返回

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

Now target is to get value of 'foo' and it should return 'bar'现在的目标是获取 'foo' 的值,它应该返回 'bar'

any help is appreciated.任何帮助表示赞赏。

I find jsx easy to use:我发现jsx易于使用:

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 .您甚至可以将其解析为Maps

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

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:您可以使用模式匹配提取 JSON 对象的属性列表,然后通过结果列表中的键查找值:

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

You can try ej module:你可以试试ej模块:

The ej module makes it easier to work with Erlang terms representing JSON in the format returned by jiffy, mochijson2, or ejson. ej 模块可以更轻松地处理以 jiffy、mochijson2 或 ejson 返回的格式表示 JSON 的 Erlang 术语。 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.您可以使用 ej:get/2 遍历对象并返回特定值,使用 ej:set/3 更新对象内的值,或使用 ej:delete/2 从对象中删除值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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