jq: 嵌套对象,提取顶级id并从内部对象中获取一个值

40

给出以下的 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
}

但是提取idstuff.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

但我再次无法理解idbook的语法;同时,我也无法使用相同的语法提取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食谱,但是似乎没有关于从另一个对象内提取项目的语法的内容。
2个回答

23

我成功地理解了它。

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

关键在于使用 newkey: .complex["key"] 的符号来进行提升。


23

有趣的是,问题确实出在"-"字符上,以下方法对我有效:

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


我似乎还在使用1.2版本。 - tripleee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接