curl http://testhost.test.com:8080/application/app/version | jq '.version' | jq '.[]'
上述命令仅输出如下值:
"madireddy@test.com"
"2323"
"test"
"02-03-2014-13:41"
"application"
如何获取密钥名称,如下所示:
email
versionID
context
date
versionName
答案 0 :(得分:104)
您可以使用:
$ 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:使用以下键创建BASH数组:
使用BASH 4 +:
mapfile -t arr < <(jq -r 'keys[]' ms.json)
在旧BASH上你可以这样做:
arr=()
while IFS='' read -r line; do
arr+=("$line")
done < <(jq 'keys[]' ms.json)
然后打印出来:
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"
答案 1 :(得分:11)
您需要使用jq 'keys[]'
。例如:
echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'
将输出以行分隔的列表:
"example1"
"example2"
"example3"
答案 2 :(得分:9)
要在JSON的更深节点上获取密钥:
echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"
答案 3 :(得分:4)
结合上面的答案,你想问jq的原始输出,所以你的最后一个过滤器应该是例如:
cat input.json | jq -r 'keys'
来自jq help:
-r output raw strings, not JSON texts;
答案 4 :(得分:1)
echo '{"ab": 1, "cd": 2}' | jq -r 'keys[]'
每行打印所有键,不带引号。
ab
cd
答案 5 :(得分:1)
要以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"
答案 6 :(得分:1)
这是用@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'
答案 7 :(得分:1)
如果您的输入是一个对象数组,
[
{
"a01" : { "name" : "A", "user" : "B" }
},
{
"a02" : { "name" : "C", "user" : "D" }
}
]
尝试:
jq '.[] | keys[]'
答案 8 :(得分:1)
奇怪的是,接受的答案实际上并没有准确回答 Q,因此作为参考,这里有一个解决方案:
$ jq -r 'keys_unsorted[]' file.json