30

鉴于以下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
 }
]

我可以轻松提取idvotes

$ 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

但又无法弄清楚idand的语法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食谱,但我似乎找不到任何关于从另一个对象内的对象内“提升”项目的语法。

4

2 回答 2

19

有趣的是,问题确实是“-”字符,这对我有用:

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

于 2014-12-19T10:10:53.613 回答
13

我设法弄清楚了。

$ jq '.[] | { id, "info-spec": .stuff["info-spec"] }' xample.json
{
  "info-spec": 12,
  "id": 12345678
}
{
  "info-spec": 23,
  "id": 12345679
}

这里的关键似乎是使用newkey: .complex["key"]符号来提升。

于 2014-12-19T09:20:52.247 回答