给出以下的 xample.json
;
[
{
"id": 12345678,
"stuff": { "book": "shelf", "hook": "line", "took": "off", "info-spec": 12 },
"votes": 23
},
{
"id": 12345679,
"stuff": { "book": "maker", "hook": "sinker", "took": "pisin", "info-spec": 23 },
"votes": 1
}
]
我可以轻松地提取出id
和votes
:$ jq '.[] | { id, votes }' xample.json
{
"votes": 23,
"id": 12345678
}
{
"votes": 1,
"id": 12345679
}
但是提取id
和stuff.info-spec
的查询应该是什么样子的?显然(对我来说)的语法根本不起作用:
$ jq '.[] | { id, stuff.info-spec }' xample.json
error: syntax error, unexpected '.', expecting '}'
.[] | { id, stuff.info-spec }
^
1 compile error
我也尝试了stuff[info-spec]
和stuff["info-spec"]
,但是,唉,我似乎不知道应该怎么做。
键名中的破折号似乎使问题更加复杂,但是我的理解有限,我可以用双引号来解决这个问题。
$ sed 's/votes/vo-tes/g' xample.json | jq '.[] | { id, "vo-tes" }'
输出结果符合预期(即类似于上面的“vo-tes”中没有破折号的情况)。
我可以提取book
:
$ jq '.[] | .stuff.book' xample.json
但我再次无法理解id
和book
的语法;同时,我也无法使用相同的语法提取info-spec
:
$ jq '.[] | .stuff."info-spec"' xample.json
error: syntax error, unexpected QQSTRING_START, expecting IDENT
.[] | .stuff."info-spec"
^
1 compile error
如果我去掉引号,那么错误信息会(可以预料到)不同:$ jq '.[] | .stuff.info-spec' xample.json
error: spec is not defined
.[] | .stuff.info-spec
^^^^
1 compile error
但是,嘿,这个方法可行:
$ jq '.[] | .stuff["info-spec"] ' xample.json
12
23
那么,我在这个例子中希望得到的输出是
{
"info-spec": 12,
"id": 12345678
}
{
"info-spec": 23,
"id": 12345679
}
我看了一下常见问题解答和jq
食谱,但是似乎没有关于从另一个对象内提取项目的语法的内容。