2014-12-19 65 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