Julinho da Adelaide Julinho da Adelaide - 5 months ago 25
Ruby Question

Ruby Json access to nested element with key

I'm trying to retrieve one value from a nested

JSON
with key.

My
JSON
structure is below:

enter image description here

If I try:

puts person_id["name"]


It does work fine, but then if I try to get the phone value as:

person_id.phone[0].["value"]


It doesn't work.

How can I properly access the
phone value
? Especially when
primary
field is
true
?

I tried this but no succcess. Thanks in advance.

Answer

From the looks of things, person_id is a hash with the string keys "name", "email", and "phone". The value with the key "phone" is an array, each element of which is a hash with the keys "label", "value", and "primary". In that case what you want is this:

phone_array = person_id["phone"]
# => [ { "label" => "Work", ... }, ... ]

first_phone = phone_array[0]
# => { "label" => "Work", ... }

first_phone_value = first_phone["value"]
# => "+0109135008"

Of course, you're looking for a way to do this in one line, which looks like this:

person_id["phone"][0]["value"]
# => "+0109135008"
Comments