鉴于以下内容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 }
我已经查看了FAQ和jq
Cookbook,但我似乎无法找到任何关于从另一个对象内的对象中"提升"项目的语法.
有趣的是,问题确实是" - "字符,这对我有用:
jq '.[] | { id, "info-spec": .stuff."info-spec" }' xample.json { "id": 12345678, "info-spec": 12 } { "id": 12345679, "info-spec": 23 }
然而你jq
似乎并不喜欢这种语法,因为它突破了以下内容并且我没有:
jq '.[] | .stuff."info-spec"' xample.json 12 23
我用:
jq --version jq-1.4
编辑:看起来像版本问题<1.4确实:https: //github.com/stedolan/jq/issues/38
我设法弄清楚了。
$ jq '.[] | { id, "info-spec": .stuff["info-spec"] }' xample.json { "info-spec": 12, "id": 12345678 } { "info-spec": 23, "id": 12345679 }
此处的关键似乎是使用newkey: .complex["key"]
符号进行提升。