【问题标题】:how do i conditionally delete specific value in specific array with jq?如何使用 jq 有条件地删除特定数组中的特定值?
【发布时间】:2023-03-17 13:31:01
【问题描述】:

这是我的 JSON 数据输入:

[
  {
    "creator": "M.W. Seo",
    "co_author": [
      "H.W. Lee",
      "S.H. Jeon",
      "M.W. Seo"
    ]
  },
  {
    "creator": "Jeffrey A. Laman",
    "co_author": [
      "Jeffrey A. Laman",
      "Mike",
      "Jackson"
    ]
  }
]

这是我想要的 JSON 数据输出:

[
  {
    "creator": "M.W. Seo",
    "co_author": [
      "H.W. Lee",
      "S.H. Jeon"
    ]
  },
  {
    "creator": "Jeffrey A. Laman",
    "co_author": [
      "Mike",
      "Jackson"
    ]
  }
]

我尝试过但不起作用的方法:

jq '.[:2]| map(if .co_author[] == .creator then del(.co_author[])' test_4.json

【问题讨论】:

    标签: json jq


    【解决方案1】:

    直接从.co_author 中的数组中减去.creator,并使用map 将其应用于顶级数组的所有元素:

    jq 'map(.co_author -= [.creator])' test_4.json 
    
    [
      {
        "creator": "M.W. Seo",
        "co_author": [
          "H.W. Lee",
          "S.H. Jeon"
        ]
      },
      {
        "creator": "Jeffrey A. Laman",
        "co_author": [
          "Mike",
          "Jackson"
        ]
      }
    ]
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多