JQ:嵌套的对象,提取顶级ID和提升内部对象的值 [英] jq: nested object, extract top-level id and lift a value from internal object

查看:257
本文介绍了JQ:嵌套的对象,提取顶级ID和提升内部对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下 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 轻松:

$ jq '.[] | { id, votes }' xample.json
{
  "votes": 23,
  "id": 12345678
}
{
  "votes": 1,
  "id": 12345679
}

不过,如果查询模样提取什么ID stuff.info规格?最明显的(对我来说)语法并不在所有的工作:

But what would the query look like to extract id and stuff.info-spec? The obvious (to me) syntax doesn't work at all:

$ jq '.[] | { id, stuff.info-spec }' xample.json
error: syntax error, unexpected '.', expecting '}'
.[] | { id, stuff.info-spec }
                 ^
1 compile error

我试过的东西[信息规格] 的东西[信息规范] 以及但是,好了,我似乎就是不要有任何想法如何应该是这样的。

I tried stuff[info-spec] and stuff["info-spec"] as well but, well, I just don't seem to have any idea how this should be done.

在键名称的破折号,似乎事情变得更加复杂,但我有限的理解是,我可以解决与双引号。

The dash in the key name seems to complicate matters even further, but my limited understanding is that I can work around that with double quotes.

$ sed 's/votes/vo-tes/g' xample.json | jq '.[] | { id, "vo-tes" }'

给出预期的输出(即类似于上面无VO-TES破折号)。

gives the expected output (i.e. similar to above without the dash in "vo-tes").

我可以提取

$ jq '.[] | .stuff.book' xample.json

但同样不能弄清楚 ID 语法;而且,我不能提取信息规格与相同的语法:

but again cannot figure out the syntax for id and book; but also, I cannot extract info-spec with the same syntax:

$ jq '.[] | .stuff."info-spec"' xample.json
error: syntax error, unexpected QQSTRING_START, expecting IDENT
.[] | .stuff."info-spec"
             ^
1 compile error

如果我拿出的报价,该错误信息是(predictably)不同:

If I take out the quotes, the error message is (predictably) different:

$ jq '.[] | .stuff.info-spec' xample.json
error: spec is not defined
.[] | .stuff.info-spec
                  ^^^^
1 compile error

但是,嘿,这个作品:

But hey, this works:

$ jq '.[] | .stuff["info-spec"] ' xample.json
12
23

我希望在这个例子中输出的话,是

My desired output for this example, then, is

{
  "info-spec": 12,
  "id": 12345678
}
{
  "info-spec": 23,
  "id": 12345679
}

我看了看常见问题解答和的 JQ 食谱,但我似乎无法找到任何关于解除从另一个对象内的对象中的项语法。

I've looked at the FAQ and the jq Cookbook but I can't seem to find anything about a syntax for "lifting" an item from within an object inside another object.

推荐答案

我设法弄明白。

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

这里的关键似乎是使用则newkey:.complex [钥匙] 记法吊装

这篇关于JQ:嵌套的对象,提取顶级ID和提升内部对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆