【问题标题】:How to do get and set values in Ruby Hashes of a given nested key?如何在给定嵌套键的 Ruby 哈希中获取和设置值?
【发布时间】: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


【解决方案1】:

试试下面的:

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

【讨论】:

  • 这是获得解决方案的更加硬编码的方式。我需要对任何 JSON 都是动态的解决方案。你可以看到你的代码和我的代码。我只写了半行。
  • 你的代码不是动态的,但我的是动态的,每次读/写都需要指定key
  • 我应该只使用这么多代码吗? json_array = JSON.parse(json) json_array.each 做 |h| #以上所有步骤将保持不变
  • 这取决于json 变量中的数据。如果json包含数组,那么你可以使用这个,但是在这个方法中,你也需要解析对象
猜你喜欢
  • 2017-05-29
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
相关资源
最近更新 更多