Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all (also nested) key names with jq

Tags:

json

jq

How can I extract all key names, even in nested objects with jq? For example, I have json:

{ "a": 1, "b": { "c": 2 } }

and I want to get list: a, b, b.c

I know that for top level keys I can get this, with: . | to_entries[] | .key, but what about keys in nested objects?

like image 359
wjtk Avatar asked Oct 04 '17 12:10

wjtk


1 Answers

Short jq solution:

jq -r '[paths | join(".")]'  jsonfile

The output:

[
  "a",
  "b",
  "b.c"
]

  • paths function outputs the paths to all the elements in its input

  • join(".") - to concatenate keys within hierarchical paths

like image 198
RomanPerekhrest Avatar answered Oct 17 '22 06:10

RomanPerekhrest