【发布时间】:2020-11-21 06:29:46
【问题描述】:
我用 vine gem 尝试过这样的事情,但没有用。有没有其他聪明的方法 注意我不想像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"}}}
预期结果是
{"name"=>"John", "address"=>{"street"=>"street 1", "country"=>"country1"}, "phone_numbers"=>[{"type"=>"tablet", "number"=>"234234"}, {"type"=>"fixed", "number"=>"2342323423"}]}
它不适用于数组,或者我遗漏了一些东西 谢谢
【问题讨论】:
-
访问
h['phone_numbers'][0]['type'] -
设置
h['phone_numbers'][0]['type'] = 'tablet' -
另一种访问方式
h.dig('phone_numbers', 0, 'type') -
我对获取和设置感兴趣,我获取的方式和我应该能够设置的方式相同。我不需要设置 h['phone_numbers'][0]['type'] = 'tablet' 的硬编码方式。我的 json 将是动态的,它每次都会改变,用户只会提供像“phone_numbers.0.type”这样的值。因此,对于任何其他说法,如果用户提供层次结构,它也应该能够设置
标签: ruby-on-rails ruby hash rubygems ruby-on-rails-5