【问题标题】:How do I modify a child object if it exists in array of objects using jq?如果子对象存在于使用 jq 的对象数组中,如何修改它?
【发布时间】:2018-07-20 10:48:28
【问题描述】:

我正在尝试使用 jq 在 API 请求或响应的各个级别修改 json 数据,以支持 API 版本控制。

这是我的(简化的)测试 JSON:

[
  {
    "note": null,
    "patient_id": 1,
    "phenotypes": [
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 1,
        "person_id": 1
      },
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 1,
        "person_id": 1
      }
    ]
  },
  {
    "note": null,
    "patient_id": 2
  },
  {
    "note": null,
    "patient_id": 3,
    "phenotypes": [
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 3,
        "person_id": 3
      },
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 3,
        "person_id": 3
      }
    ]
  }
]

我有一个对象数组。每个对象可能有"phenotypes",我需要修改它的内容,以及从顶级对象中删除"note"

目前我的jq如下:

[ map(del(.note, .age)) | .[] | select(.phenotypes != null) | .phenotypes |= map(del(.person_id)) ]

这几乎可行,但由于select(.phenotypes != null),数组中的第二个对象在过滤后永远不会返回。

我也尝试过使用 if-then-else (end),但是我不能让它不出错,而且我找不到任何示例或文档表明它可以用于进一步表达。

我的预期输出如下:

[
  {
    "patient_id": 1,
    "phenotypes": [
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 1
      },
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 1
      }
    ]
  },
  {
    "patient_id": 2
  },
  {
    "patient_id": 3,
    "phenotypes": [
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 3
      },
      {
        "name": "Breast carcinoma",
        "observation": "present",
        "patient_id": 3
      }
    ]
  }
]

note 已从根目录中删除。 person_id 已从 phenotypes 中删除。

【问题讨论】:

  • 我已经包含了预期的输出。谢谢。

标签: json edit jq


【解决方案1】:

这对我有用:

map(del(.note, .age)) |
map( 
    if .phenotypes then 
        (.phenotypes |= map(del(.person_id)))
    else
        .
    end 
)

Working example

【讨论】:

  • 我想当我尝试使用if 时,我并没有意识到else 是必需的。
  • 我试图使用.phenotypes? 解决它,但无法坚持。这种方法可能不是那么优雅,但总有多种方法可以解决这些问题。
  • 我看到了其他建议类似的答案,但我也无法做到这一点。我也尝试了`// []`来解决空问题,但它也不喜欢那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
相关资源
最近更新 更多