curiousity
curiousity

Reputation: 179

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

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.

Upvotes: 0

Views: 1218

Answers (2)

ikegami
ikegami

Reputation: 385506

paths( objects | .ENTITY == "TEXT" )

Format the output as desired. For example,

jq -r 'paths( objects | .ENTITY == "TEXT" ) | join(".")'

jqplay


[The following consists of my original answer]

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

Upvotes: 2

pmf
pmf

Reputation: 36033

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]
'

Upvotes: -1

Related Questions