Get all unique JSON key names with JQ

Is there a way to get all unique key names without causing a unique view outside jq?

file example:

{"a": 1, "b": 2, "c": 3}
{"a": 4, "b": 5, "d": 6}

Both jq and the sort command, as I am using it now, but I think it is not so efficient:

jq -r keys[] example | sort -u                                                                               
a                                                                                                                                       
b                                                                                                                                       
c                                                                                                                                       
d     
+5
source share
2 answers

Of course.

$ jq -n '[inputs | keys[]] | unique | sort' input.json
[
  "a",
  "b",
  "c",
  "d"
]

Here is another option that might work better since it does not require collecting keys into an array.

$ jq -n 'reduce (inputs | keys[]) as $k ({}; .[$k] = null) | keys' input.json

Or maybe even better:

$ jq -n 'foreach (inputs | keys[]) as $k ({}; .[$k]+=1; if .[$k]==1 then $k else empty end)' input.json
+7
source

Two points:

  1. The original solution, using jq and then sort, is efficient, especially regarding memory usage. (A solution that includes the -s option actually causes the entire file to be read into memory).

  2. JQ unique sort. unique|sort unique .

+2

Source: https://habr.com/ru/post/1584247/


All Articles