【问题标题】:Ruby Array Select - Nested Maps with WildcardRuby Array Select - 带有通配符的嵌套映射
【发布时间】:2020-04-30 16:38:07
【问题描述】:

我有一个 JSON 响应,我想跨多个索引提取给定键的值。

json_object['resources'].select {|a| a["type"] == "aws_subnet" && a["name"] == "private"}.first["instances"]

这让我得到了一个实例数组。每个实例都包含一个属性映射元素,然后该元素包含一个 ID 元素。我要做的就是获取所有 ID 的数组。执行以下操作:

json_object['resources'].select {|a| a["type"] == "aws_subnet" && a["name"] == "private"}.first["instances"][0..3]["attributes"]["id"]

让我害怕:

TypeError (no implicit conversion of String into Integer)

【问题讨论】:

  • 你能提供json_object的样本吗?
  • 错误信息告诉您,您正在尝试将 String 用作整数,您只需在该变量上添加 .to_i 即可。

标签: arrays json ruby amazon-web-services


【解决方案1】:

看看你是如何构建语句的,问题在于你的范围选择 - [0..3]

范围选择将返回array,而不是hash

尝试从 array 获取 ["attributes"] 会引发 TypeError,因为数组的索引是 Integers,而不是 Strings。

要解决这个问题,我建议使用map 函数来迭代实例,获取每个实例的 id 值:

json_object['resources'].select {|a| a["type"] == "aws_subnet" && a["name"] == "private"}.first["instances"][0..3].map { |inst| inst["attributes"]["id"] }

另外,如果您想优化,我建议使用find 而不是select,后跟firstfind 查找第一个匹配项,它完成了同样的事情,但性能更好。

有了它,这就是你要找的东西:

ids = json_object['resources'].find {|a| a["type"] == "aws_subnet" && a["name"] == "private"}["instances"][0..3].map { |inst| inst["attributes"]["id"] }

注意:根据 Thang 的评论,将来包含您尝试解析的 JSON 响应的示例会很有帮助,以便我们确保答案有效

【讨论】:

  • 这正是我想要的。我觉得我需要使用地图,但语法不太正确。
猜你喜欢
  • 2013-03-21
  • 2022-06-15
  • 1970-01-01
  • 2017-11-07
  • 2021-07-06
  • 1970-01-01
  • 2019-12-27
  • 2021-03-01
  • 2016-09-13
相关资源
最近更新 更多