Home > other >  Finding the path to all occurrences of a specific key is a specify value
Finding the path to all occurrences of a specific key is a specify value

Time:10-13

I have a bunch of hundred thousand line json files, and I'm trying to work how out they are structured.

I'd like to print the path to all keys named "ENTITY" with a value "TEXT".

these can be nested at any level. There are lots of examples for finding one at a particular level, e.g. Select objects based on value of variable in object using jq

But I'm actually trying to figure out where these items are nested, since the file is so large, I can't do it by inspection.

CodePudding user response:

path( .. | select( type=="object" and .ENTITY == "TEXT" ) )

Format the output as desired. For example,

jq -r 'path( .. | select( type=="object" and .ENTITY == "TEXT" ) ) | join(".")'

jqplay

CodePudding user response:

If I understood your question correctly, you are searching for leafs with a given key/field whose value matches a given value. This approach uses leaf_paths to get all leafs along with getpath to get their values, transpose to tuple them up, and finally select to reduce the list to those matching the criteria. The output is only the path arrays.

jq --arg key "ENTITY" --arg value "TEXT" '
  [[leaf_paths],[getpath(leaf_paths)]]
  | transpose
  | map(select(.[0][-1] == $key and .[1] == $value))[][0]
'
  • Related