jq - How to iterate through keys of different names

31,020

Solution 1

The original tag for this question was jq so here is a jq solution:

.[] | keys[]

For example, with the input as shown in the question:

$ jq '.[] | keys[]' input.json

"identifier1"
"identifier2"

To retrieve the key names in the order they appear in the JSON object, use keys_unsorted.

Solution 2

I'd think something along these lines would work well:

jq '. | to_entries | .[].key'

see https://stedolan.github.io/jq/manual/#to_entries,from_entries,with_entries

or if you wanted to get the values from a variable:

JSON_DATA={main:{k1:v1,k2:v2}}
result=$(jq -n "$JSON_DATA" | jq '.main | to_entries | .[].value' --raw-output)
echo $result

##outputs: v1 v2

Solution 3

I came here hoping to sort out a bunch of keys from my JSON, I found two features handy. There are three functions "to_entries", "from_entries", and "with_entries". You can filter the values by key or value, like so:

JSON_DATA='
{
  "fields": {
    "first": null,
    "second": "two",
    "third": "three"
  }
}
'

echo "$JSON_DATA" | jq '{fields: .fields | with_entries(select(.value != null and .key != "third")) }'

Output:

{
  "fields": {
    "second": "two"
  }
}
Share:
31,020
Adam vonNieda
Author by

Adam vonNieda

I like Jenkins and Linux. I make my living being good at Oracle stuff.

Updated on August 10, 2020

Comments

  • Adam vonNieda
    Adam vonNieda almost 4 years

    I've got JSON that looks like this

    {
      "keyword1": {
        "identifier1": 16
      },
      "keyword2": {
        "identifier2": 16
      }
    }
    

    and I need to loop through the keywords to get the identifiers (not sure if I'm using the right terminology here). Seems pretty simple, but because the keywords are all named different, I don't know how to handle that.