【问题标题】:jq: nested object, extract top-level id and lift a value from internal objectjq:嵌套对象,提取顶级 id 并从内部对象中提取值
【发布时间】:2015-02-18 04:12:50
【问题描述】:

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

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

【问题讨论】:

    标签: json bash jq


    【解决方案1】:

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

    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
    

    edit:看起来确实是 https://github.com/stedolan/jq/issues/38

    【讨论】:

    • 看来我还在使用 1.2。
    【解决方案2】:

    我设法弄明白了。

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

    这里的关键似乎是使用newkey: .complex["key"] 表示法进行提升。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      相关资源
      最近更新 更多