【问题标题】:Can't extract data from parsed JSON Hash in ruby无法从 ruby​​ 中解析的 JSON Hash 中提取数据
【发布时间】:2020-01-23 09:08:35
【问题描述】:

我正在尝试从此 API 响应中提取元素,但由于某种原因我无法做到。我有以下 API 响应正文: `

[
  {
    "ID": "295699",
    "restriction": [
      {
        "restrictionTypeCode": "10001"
      }
    ]
  }
]

` 现在,我只想打印restrictionTypeCode

  json_string = RestClient.get "#{$uri}", {:content_type => 'application/json'}
  hash = JSON.parse(json_string) 
  code= hash['restriction']['restrictionTypeCode']
  puts code

上面的代码出错了,没有显示restrictionTypeCode

【问题讨论】:

  • 引发了什么错误?出自哪条线?你能粘贴堆栈跟踪吗?
  • 谢谢@mrzasa。我更新了你的代码,但现在我在控制台中得到 Nil 值 $uri = "URL" $json_string = RestClient.get "#{$uri}", {:content_type => 'application/json'} $hash = JSON .parse($json_string) puts $hash.first&.dig(:restriction)&.first&.dig(:restrictionTypeCode) puts $hash.flat_map { |hsh| hsh[:restriction]&.map { |sub_hsh| sub_hsh[:restrictionTypeCode] } } 。当我输出 $json_string 或哈希时,我可以看到整个响应。但是当我输出您提供的 2 行时,我在控制台中为上面的两个“放置”得到空的 2 行
  • 不是我,是 @SRack 帮助你 :)

标签: json ruby parsing hash extract


【解决方案1】:

您的问题是您的数据在某些地方返回数组。请尝试以下操作:

data = [
  {
    "ID": "295699",
    "restriction": [
      {
        "restrictionTypeCode": "10001"
      }
    ]
  }
]

data.first[:restriction].first[:restrictionTypeCode]
# to make this safe from any nil values you may encounter, you might want to use
data.first&.dig(:restriction)&.first&.dig(:restrictionTypeCode)
# => "10001"

# or 

data.flat_map { |hsh| hsh[:restriction]&.map { |sub_hsh| sub_hsh[:restrictionTypeCode] } }
# => ["10001"]

稍微分解一下,您的顶级响应和位于键 :restriction 下的响应都返回数组;因此,要从它们那里获取数据,您需要访问它们包含的其中一项(在我的示例中使用 first)或映射它们(第二个示例)。

我在其中添加了一些nil 值检查:这在处理 API 响应时非常重要,因为您无法控制数据,因此无法确定所有字段都会出现。如果遇到这样的数据,您不会抛出错误,而是会返回 nil 以避免破坏后续代码。

希望这会有所帮助 - 如果您有任何问题,请告诉我:)

【讨论】:

  • hash.first['restriction'].first['restrictionTypeCode']
  • 也很可能是符号,而不是字符串作为键
  • 谢谢@mrzasa - 很好。我会更新的。非常感谢:)
  • 这个@DeanE 相处得怎么样?
猜你喜欢
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 2017-07-30
  • 1970-01-01
相关资源
最近更新 更多