【问题标题】:Ruby get values from nested json response by using the json gemRuby 使用 json gem 从嵌套的 json 响应中获取值
【发布时间】:2018-05-28 10:50:08
【问题描述】:

我有一个这样的 json 响应:

@response = {"result":{"amount":0.0}}

如何将金额的值放入变量中?

我试过了:

@response['result']['amount']
@response['result'][0] 
@response[0][0] 

我正在使用 json gem。

【问题讨论】:

  • 我得到这个@response = {"result":{"amount":0.0}}的语法错误
  • 您确实可以使用括号符号[] 来访问来自 json 响应的值。只需通过调用@response.keys 来检查可以传递到[] 的所有可用密钥。

标签: json ruby


【解决方案1】:

试试这个

@response[:result][:amount]

@response 对象中的键是 :symbols 而不是 strings

欲了解更多信息:What's the difference between a string and a symbol in Ruby?

【讨论】:

    【解决方案2】:

    使用嵌套哈希,Ruby 的 Hash#dig 方法非常方便,因为如果任何中间步骤为 nil,它就会返回 nil。

    @response.dig(:result, :amount)
    

    如果您不确定密钥字符串或符号是什么,您可以使用提供Hash#with_indifferent_accessActiveSupport::HashWithIndifferentAccess(Rails 将默认包含此内容)。然后你就可以用符号和字符串格式的键来获取值了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-08
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      相关资源
      最近更新 更多