Curl http://testhost.test.com:8080/application/app/version | jq '。版本' | jq '.[]'
上面的命令只输出如下值:
"madireddy@test.com"
"2323"
"test"
"02-03-2014-13:41"
"application"
我怎样才能得到像下面这样的键名:
email
versionID
context
date
versionName
Curl http://testhost.test.com:8080/application/app/version | jq '。版本' | jq '.[]'
上面的命令只输出如下值:
"madireddy@test.com"
"2323"
"test"
"02-03-2014-13:41"
"application"
我怎样才能得到像下面这样的键名:
email
versionID
context
date
versionName
当前回答
要按键在原始JSON中出现的顺序获取键,请使用:
jq 'keys_unsorted' file.json
如果你想要键按字母数字排序,你可以使用:
jq 'keys' file.json
完整的示例
$ 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"
]
其他回答
将一行中的键打印为csv格式:
echo '{"b":"2","a":"1"}' | jq -r 'keys | [ .[] | tostring ] | @csv'
输出:
"a","b"
为了csv的完整性…将一行中的值打印为csv格式:
echo '{"b":"2","a":"1"}' | jq -rS . | jq -r '. | [ .[] | tostring ] | @csv'
输出:
"1","2"
Echo '{"ab": 1, "cd": 2}' | jq -r 'keys[]'打印所有键每行一个键,不带引号。
ab
cd
下面是@anubhava在他的回答中给出的JSON示例获得Bash数组的另一种方式:
arr=($(jq --raw-output 'keys_unsorted | @sh' file.json))
echo ${arr[0]} # 'Archiver-Version'
echo ${arr[1]} # 'Build-Id'
echo ${arr[2]} # 'Build-Jdk'
如果你的输入是一个对象数组,
[
{
"a01" : { "name" : "A", "user" : "B" }
},
{
"a02" : { "name" : "C", "user" : "D" }
}
]
试一试:
jq '.[] | keys[]'
奇怪的是,公认的答案实际上并没有准确地回答问题,所以作为参考,这里有一个解决方案:
$ jq -r 'keys_unsorted[]' file.json