Home > Software design >  How to return a key if the value equal to specific value using jq in json parsing
How to return a key if the value equal to specific value using jq in json parsing

Time:12-17

I have json file like this

{
  "version": "4.6.0",
  "flags": {
    "T1": true,
    "T1c": false,
    "T2": false,
    "FLAIR": false
  },
  "shapes": [],
  "imagePath": "HC-002_LM-0000_aparc aseg_1mm_bin.png",
  "imageData":xxxxxxxxx
}

and I need the output to be

T1

as the value is true, Please suggest correct use of jq here, thanks!

CodePudding user response:

Use to_entries to access field name and value of an object's items and select those you need:

jq --raw-output '.flags | to_entries[] | select(.value).key' 
T1

Demo

CodePudding user response:

Here is a ruby:

ruby -r JSON -e 'd=JSON.parse($<.read)
puts "T1" if d["flags"]["T1"]
' file
T1
  • Related