简体   繁体   中英

How to do get and set values in Ruby Hashes of a given nested key?

I tried something like this with vine gem but not working. Is there any other smart way Note i do not want to use complex Hash Class like we have here

require 'vine'
require 'json'

json = '{
   "name":"John",
   "address":{
      "street":"street 1",
      "country":"country1"
   },
   "phone_numbers":[
      {
         "type":"mobile",
         "number":"234234"
      },
      {
         "type":"fixed",
         "number":"2342323423"
      }
   ]
}'

h = JSON.parse(json)

{"name"=>"John", "address"=>{"street"=>"street 1", "country"=>"country1"}, "phone_numbers"=>[{"type"=>"mobile", "number"=>"234234"}, {"type"=>"fixed", "number"=>"2342323423"}]}

a = h.access("phone_numbers.0.type")

mobile

b = h.set("phone_numbers.0.type", "tablet")

{"name"=>"John", "address"=>{"street"=>"street 1", "country"=>"country1"}, "phone_numbers"=>{0=>{:type=>"tablet"}}}

expected result is

{"name"=>"John", "address"=>{"street"=>"street 1", "country"=>"country1"}, "phone_numbers"=>[{"type"=>"tablet", "number"=>"234234"}, {"type"=>"fixed", "number"=>"2342323423"}]}

It is not working for array, or i am missing something Thanks

Try the below:

require 'json'

#considering that the json is same as you mentioned in the question

h = JSON.parse(json)

# For accessing name 
p h['name']
#for changing the name 
h['name'] = 'ABC'

# for getting address
p h['address']['street']
# for setting address 
h['address']['street'] = "my street"

#get phone number
h['phone_numbers'].each do |ph|
  p ph['type']
  #Set mobile number
  ph['number'] = "123"
end

In the above you received a single object in json .

But in case if you receive multiple objects, then parse them like below

json_array = JSON.parse(json)

json_array.each do |h|
 #All the above steps will remain same
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM