jsonshellunixkeyjq

How to get key names from JSON using jq


curl http://testhost.test.com:8080/application/app/version | jq '.version' | jq '.[]'

The above command outputs only the values as below:

"madireddy@test.com"

"2323"

"test"

"02-03-2014-13:41"

"application"

How can I get the key names instead like the below:

email

versionID

context

date

versionName

Solution

  • To get the keys in the order they appear in the original JSON use:

    jq 'keys_unsorted' file.json
    

    If you want the keys sorted alphanumerically, you can use:

    jq 'keys' file.json
    

    Complete example

    $ cat file.json
    { "Created-By" : "Apache Maven", "Build-Number" : "", "Archiver-Version" : "Plexus Archiver", "Build-Id" : "",  "Build-Tag" : "", "Built-By" : "cporter"}
    
    $ jq 'keys_unsorted' file.json                                         
    [
      "Created-By",
      "Build-Number",
      "Archiver-Version",
      "Build-Id",
      "Build-Tag",
      "Built-By"
    ]
    
    $ jq 'keys' file.json
    [
      "Archiver-Version",
      "Build-Id",
      "Build-Number",
      "Build-Tag",
      "Built-By",
      "Created-By"
    ]