代码之家  ›  专栏  ›  技术社区  ›  Relequestual

如果子对象存在于使用JQ的对象数组中,我如何修改它?

  •  2
  • Relequestual  · 技术社区  · 7 年前

    我尝试使用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 .

    1 回复  |  直到 7 年前
        1
  •  3
  •   Remy Sharp    7 年前

    这对我很有用:

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

    Working example