Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json jq:嵌套对象,提取顶级id并从内部对象中提升值_Json_Bash_Jq - Fatal编程技术网

Json jq:嵌套对象,提取顶级id并从内部对象中提升值

Json jq:嵌套对象,提取顶级id并从内部对象中提升值,json,bash,jq,Json,Bash,Jq,给定以下example.json [ { "id": 12345678, "stuff": { "book": "shelf", "hook": "line", "took": "off", "info-spec": 12 }, "votes": 23 }, { "i

给定以下
example.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 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”中没有破折号)

我可以提取

$ 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
}

我查看了和,但似乎找不到任何关于从另一个对象中的对象中“提升”项目的语法。

我设法找到了它

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

这里的关键似乎是使用
newkey:.complex[“key”]
符号进行提升。

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

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.2上。