4

I can get top-level JSON keys with jq as

jq 'keys'

E.g., see this question: Get key names from JSON file using jq

And I can enable recursion in jq:

jq '..'

As in: Recursive search values by key

But jq '.. | keys' returns jq: error at <stdin> string has no keys.

peak
  • 105,803
  • 17
  • 152
  • 177
Anton Tarasenko
  • 8,099
  • 11
  • 66
  • 91

2 Answers2

14

Just ignore keys when they are absent for some values in JSON:

jq '.. | keys?'
Anton Tarasenko
  • 8,099
  • 11
  • 66
  • 91
  • 1
    this doesn't cleanly work with arrays of objects: $ echo '{ "array1" : [ { "obj" : "data"} ] }' | jq '.. | keys?' produces: [ "array1" ] [ 0 ] [ "obj" ] – Jason Harrison Aug 25 '20 at 16:26
1

Ignore non-objects when inspecting for key names:

jq -r '.. | if type == "object" then to_entries[] | .key else empty end' "${LOCALAPPDATA}/Google/Chrome/User Data/default/Bookmarks" | sort --uniq
bookmark_bar
checksum
children
date_added
date_modified
guid
id
name
other
roots
synced
type
url
version
Kim Taylor
  • 348
  • 1
  • 10