Want to access an element from the tuple inside bitsrting inside list

Steve Vinoski steve at basho.com
Mon May 19 08:07:50 EDT 2014


On Mon, May 19, 2014 at 4:04 AM, Gopi Krishna <gopi at lintelindia.com> wrote:

> Hi All,
>
> I am having the data like:
>
> R =
> [<<"{\"age\": 24, \"name\": \"krishna\"}">>,
>  <<"{\"age\": 29, \"name\": \"sharat\"}">>,
>  <<"{\"age\": 25, \"name\": \"ramesh\"}">>,
>  <<"{\"age\": 28, \"name\": \"kumar\"}">>,
>  <<"{\"age\": 24, \"name\": \"gopi\"}">>,
>  <<"{\"age\": 27, \"name\": \"anil\"}">>].
>
> How can i get the age,name value for a particular age/name.
>

Each item in the list is an Erlang binary containing JSON data. You need to
decode the JSON into an Erlang data type to have practical access to the
fields.

I have tried the following but i am not sure how to get it.
>
> 28> list_to_tuple(R).
> {<<"{\"age\": 24, \"name\": \"krishna\"}">>,
>  <<"{\"age\": 29, \"name\": \"sharat\"}">>,
>  <<"{\"age\": 25, \"name\": \"ramesh\"}">>,
>  <<"{\"age\": 28, \"name\": \"kumar\"}">>,
>  <<"{\"age\": 24, \"name\": \"gopi\"}">>,
>  <<"{\"age\": 27, \"name\": \"anil\"}">>}
>
> element(1,Tup).
> <<"{\"age\": 24, \"name\": \"krishna\"}">>
>

Conversion to a tuple is unnecessary. As the answer to your StackOverflow
question on this topic indicates, you need a JSON parser. That answer
recommends jiffy, but any JSON parser will do. The code below uses jsx from
https://github.com/talentdeficit/jsx to extract each element of the R list
as JSON (in command 2), and to also extract the age element from each
element (in command 3). Both 2 and 3 use Erlang list comprehensions to
process each element of the R list.

--steve

1> R =
1> [<<"{\"age\": 24, \"name\": \"krishna\"}">>,
1>  <<"{\"age\": 29, \"name\": \"sharat\"}">>,
1>  <<"{\"age\": 25, \"name\": \"ramesh\"}">>,
1>  <<"{\"age\": 28, \"name\": \"kumar\"}">>,
1>  <<"{\"age\": 24, \"name\": \"gopi\"}">>,
1>  <<"{\"age\": 27, \"name\": \"anil\"}">>].
[<<"{\"age\": 24, \"name\": \"krishna\"}">>,
 <<"{\"age\": 29, \"name\": \"sharat\"}">>,
 <<"{\"age\": 25, \"name\": \"ramesh\"}">>,
 <<"{\"age\": 28, \"name\": \"kumar\"}">>,
 <<"{\"age\": 24, \"name\": \"gopi\"}">>,
 <<"{\"age\": 27, \"name\": \"anil\"}">>]
2> [jsx:decode(J) || J <- R].
[[{<<"age">>,24},{<<"name">>,<<"krishna">>}],
 [{<<"age">>,29},{<<"name">>,<<"sharat">>}],
 [{<<"age">>,25},{<<"name">>,<<"ramesh">>}],
 [{<<"age">>,28},{<<"name">>,<<"kumar">>}],
 [{<<"age">>,24},{<<"name">>,<<"gopi">>}],
 [{<<"age">>,27},{<<"name">>,<<"anil">>}]]
3> [lists:keysearch(<<"age">>, 1, jsx:decode(J)) || J <- R].
[{value,{<<"age">>,24}},
 {value,{<<"age">>,29}},
 {value,{<<"age">>,25}},
 {value,{<<"age">>,28}},
 {value,{<<"age">>,24}},
 {value,{<<"age">>,27}}]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.basho.com/pipermail/riak-users_lists.basho.com/attachments/20140519/4dbb542c/attachment.html>


More information about the riak-users mailing list