简体   繁体   中英

Remove JSON element if key equals true (jq)

Given JSON:

[
  {
    "1": "false"
    "2": "true",
    "3": "true"
  },
  {
    "1": "false"
    "2": "false",
    "3": "false"
  },
  {
    "1": "true"
    "2": "true",
    "3": "true"
  }
]

Given array as an argument passed to jq:

["1","2","3"]

Need to remove JSON element using jq tool if at least one key is not "true".

Desired output:

[
  {
    "1": "false"
    "2": "true",
    "3": "true"
  },
  {
    "1": "true"
    "2": "true",
    "3": "true"
  }
]

Given JSON:

[
  {
    "1": "false"
    "2": "true",
    "3": "true"
  },
  {
    "1": "false"
    "2": "false",
    "3": "false"
  },
  {
    "1": "true"
    "2": "true",
    "3": "true"
  }
]

Given array as an argument passed to jq:

["1","2","3"]

Need to remove JSON element using jq tool if at least one key is not "true".

Desired output:

[
  {
    "1": "false"
    "2": "true",
    "3": "true"
  },
  {
    "1": "true"
    "2": "true",
    "3": "true"
  }
]

I don't know what role the argument ["1","2","3"] should play, but apart from that, you can convert the object items from string to boolean using fromjson , then aggregate them appropriately, and use this result in a map(select(…)) clause to filter the input array.

Now, if you want to remove items

if at least one key is not "true"

meaning you want to keep only those that are entirely true , use the all aggregator:

jq 'map(select(map(fromjson) | all))'
[
  {
    "1": "true",
    "2": "true",
    "3": "true"
  }
]

Demo

But if, as your desired output suggests, you want to remove those items that are entirely false , meaning to keep only those where there is at least one value which is true , use the any aggregator:

jq 'map(select(map(fromjson) | any))'
[
  {
    "1": "false",
    "2": "true",
    "3": "true"
  },
  {
    "1": "true",
    "2": "true",
    "3": "true"
  }
]

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM