如何在给定嵌套键的Ruby哈希中获取和设置值



我在vine gem上尝试过这样的操作,但没有成功。还有其他聪明的方法吗注意,我不想像这里那样使用复杂的哈希类

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"}}}

预期结果是

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

它不适用于数组,或者我缺少了一些东西感谢

尝试以下操作:

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

在上面的内容中,您在json中收到了一个对象。

但如果你收到多个对象,那么像下面的一样解析它们

json_array = JSON.parse(json)
json_array.each do |h|
#All the above steps will remain same
end

最新更新