Bootstrap FreeKB - jq - Parse JSON keys
jq - Parse JSON keys

Updated:   |  jq articles

Let's say my.json contains the following, where there are a few keys.

{
  "fruits": [
    "apple",
    "banana",
    "grapes"
  ],
  "veggies": [
    "onion",
    "pepper",
    "carrot"
  ],
  "grains": [
    "rice",
    "couscous",
    "quinoa"
  ]
}

 

Here is how you can parse my.json.

]$ jq '' my.json
{
  "fruits": [
    "apple",
    "banana",
    "grapes"
  ],
  "veggies": [
    "onion",
    "pepper",
    "carrot"
  ],
  "grains": [
    "rice",
    "couscous",
    "quinoa"
  ]
}

 

keys can be used to return the keys as a list.

]$ jq 'keys' my.json
[
  "fruits",
  "grains",
  "veggies"
]

 

Here is how you can just get the keys in the list.

]$ jq 'keys[]' my.json
"fruits"
"grains"
"veggies"

 

Index numbers can be used to return a specific key.

]$ jq 'keys[0]' my.json
"fruits"

 

Here is how you can loop over each key.

]$ jq 'keys[]' my.json | while read key; do echo $key; done;
"fruits"
"grains"
"veggies"

 

Or like this.

]$ while read key; do echo $key; done < <(jq 'keys[]' my.json)
"fruits"
"grains"
"veggies"

 

To eliminate the double quotes, the -r or --raw-output flag can be used.

]$ jq --raw-output 'keys[]' my.json | while read key; do echo $key; done;
fruits
grains
veggies

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ff0974 in the box below so that we can be sure you are a human.