1

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.

Community
  • 1
  • 1
Julinho da Adelaide
  • 386
  • 2
  • 5
  • 15
  • 1
    Welcome to Stack Overflow. Don't use an image to represent data that acts as input to your code. We can't reuse that and have to type it in, which immediately turns off potential help for you. Also, the link can rot then break, leaving your question making no sense. Please read "[ask]" including the linked pages, and "[mcve]". – the Tin Man Jun 29 '16 at 20:40
  • 1
    @the Tin Man has explained why you should not post images of code. I downvoted your question because you have seen his comment but elected to ignore his advice. You should do as he suggests even though you have selected an answer, as many SO members may read your question in future. Also, please remove the dashes and assign a variable to the hash (e.g., `hash = {...}`), so that readers can both cut and paste and refer to the variable without having to define it. I will remove my downvote it you edit. – Cary Swoveland Jun 29 '16 at 21:43

2 Answers2

3

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"
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • Thanks Jordan. It really worked. And then I dont need to make any change to get the active phone since the current phone will be always on 0 level. Thanks again. – Julinho da Adelaide Jun 29 '16 at 18:49
3

The only problem with your code was that you tried to use a dot-method accessor .phone when you should have used hash-key accessor ["phone"].

This is an understandable mistake. It'd work in Javascript.

It's actually not difficult to add this functionality. Ruby has the OpenStruct class which is a Hash-like object that automatically adds dot-method accessors. You'll just need to require ostruct, which is part of the standard lib.

You can tell JSON.parse to automatically convert all Hashes to OpenStructs (source):

object = JSON.parse(json, object_class: OpenStruct)

Or you can use the recursive-open-struct gem:

RecursiveOpenStruct.new(nested_hash)
max pleaner
  • 26,189
  • 9
  • 66
  • 118