sudal
sudal

Reputation: 1

how do i conditionally delete specific value in specific array with jq?

This is my JSON data input:

[
  {
    "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"
    ]
  }
]

This is my desired JSON data output:

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

What I have tried but is not working:

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

Upvotes: 0

Views: 193

Answers (1)

pmf
pmf

Reputation: 36261

Subtract .creator directly from the array in .co_author and apply this to all elements of the top-level array using 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

Upvotes: 2

Related Questions