鉴于以下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
and的语法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
}