2014-12-19 89 views
6

给定以下xample.json;jq:嵌套对象,提取顶级id并从内部对象提取值

[ 
{ 
    "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,但我似乎无法找到任何有关从另一个对象内的对象内“提升”某个项目的语法的任何操作。

回答

1

我设法弄清楚了。

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

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

4

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

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

+0

我似乎仍然在1.2。 – tripleee 2014-12-19 10:13:28

+1

是的,刚刚编辑:https://github.com/stedolan/jq/issues/38 – 2014-12-19 10:14:25