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
You can use:
$ jq 'keys' file.json
$ cat file.json:
{ "Archiver-Version" : "Plexus Archiver", "Build-Id" : "", "Build-Jdk" : "1.7.0_07", "Build-Number" : "", "Build-Tag" : "", "Built-By" : "cporter", "Created-By" : "Apache Maven", "Implementation-Title" : "northstar", "Implementation-Vendor-Id" : "com.test.testPack", "Implementation-Version" : "testBox", "Manifest-Version" : "1.0", "appname" : "testApp", "build-date" : "02-03-2014-13:41", "version" : "testBox" }
$ jq 'keys' file.json
[
"Archiver-Version",
"Build-Id",
"Build-Jdk",
"Build-Number",
"Build-Tag",
"Built-By",
"Created-By",
"Implementation-Title",
"Implementation-Vendor-Id",
"Implementation-Version",
"Manifest-Version",
"appname",
"build-date",
"version"
]
UPDATE: To create a BASH array using these keys:
Using BASH 4+:
mapfile -t arr < <(jq -r 'keys[]' ms.json)
On older BASH you can do:
arr=()
while IFS='' read -r line; do
arr+=("$line")
done < <(jq 'keys[]' ms.json)
Then print it:
printf "%s\n" ${arr[@]}
"Archiver-Version"
"Build-Id"
"Build-Jdk"
"Build-Number"
"Build-Tag"
"Built-By"
"Created-By"
"Implementation-Title"
"Implementation-Vendor-Id"
"Implementation-Version"
"Manifest-Version"
"appname"
"build-date"
"version"
Thank you it worked! I am assigning these values into array in Shell script like array=($keyContents) but its not assigning properly, Is there any way to assign values to arrays mentioning delimiters?
Whenever the key/value has space in it, array is treating it as new value, I replaced spaces with _ which resolved the issue. Thank you very much! but now one more problem. : ( I am getting different orders when i get keys alone and when i get values alone : (
Use
mapfile -t arr < <(jq -r 'keys[]' ms.json)
instead of that ugly process substitution to avoid having problems with spaces in the keys.@anubhava, if mapfile is unavailable a good old
arr=(); while IFS='' read -r line; do arr+=("$line"); done < <(...)
will also do.Might want to mention
keys_unsorted
to get the keys in document order.