Reputation: 1065
I have a tuple list that look like this:
{[{<<"id">>,1},
{<<"alerts_count">>,0},
{<<"username">>,<<"santiagopoli">>},
{<<"facebook_name">>,<<"Santiago Ignacio Poli">>},
{<<"lives">>,{[{<<"quantity">>,8},
{<<"max">>,8},
{<<"unlimited">>,true}]}}]}
I want to know how to extract properties from that tuple. For example:
get_value("id",TupleList), %% should return 1.
get_value("facebook_name",TupleList), %% should return "Santiago Ignacio Poli".
get_value("lives"), %% should return another TupleList, so i can call
get_value("quantity",get_value("lives",TupleList)).
I tried to match all the "properties" to a record called "User" but I don't know how to do it.
To be more specific: I used the Jiffy library (github.com/davisp/jiffy) to parse a JSON. Now i want to obtain a value from that JSON.
Thanks!
Upvotes: 1
Views: 2515
Reputation: 13164
The first strange thing is that the tuple contains a single item list: where [{Key, Value}]
is embedded in {}
for no reason. So let's reference all that stuff you wrote as a variable called Stuff
, and pull it out:
{KVList} = Stuff
Good start. Now we are dealing with a {Key, Value}
type list. With that done, we can now do:
lists:keyfind(<<"id">>, 1, KVList)
or alternately:
proplists:get_value(<<"id">>, KVList)
...and we would get the first answer you asked about. (Note the difference in what the two might return if the Key isn't in the KVList before you copypasta some code from here...).
A further examination of this particular style of question gets into two distinctly different areas:
{Key, Value}
functions (hint: the lists
, proplists
, orddict
, and any other modules based on the same concept is a good candidate for research, all in the standard library), including basic filter and map.Upvotes: 2
Reputation: 3584
You should look into proplists module and their proplist:get_value/2
function.
You just need to think how it should behave when Key
is not present in the list (or is the default proplists behavior satisfying).
And two notes:
<<"id">>
in your functionproplists works on lists, but data you presented is list inside one element tuple. So you need to extract this you Data
.
{PropList} = Data,
Id = proplists:get_value(<<"id">>, PropList),
Upvotes: 0