给定以下xample.json
;jq:嵌套对象,提取顶级id并从内部对象提取值
[
{
"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
}
我看过FAQ和jq
Cookbook,但我似乎无法找到任何有关从另一个对象内的对象内“提升”某个项目的语法的任何操作。
我似乎仍然在1.2。 – tripleee 2014-12-19 10:13:28
是的,刚刚编辑:https://github.com/stedolan/jq/issues/38 – 2014-12-19 10:14:25