Julinho da Adelaide Julinho da Adelaide - 1 year ago 89
Ruby Question

Ruby Json access to nested element with key

I'm trying to retrieve one value from a nested

with key.

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:


It doesn't work.

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

I tried this but no succcess. Thanks in advance.

Answer Source

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:

# => "+0109135008"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download