2016-09-30 62 views
3

鍵值我有一個看起來如下文件:使用JQ來從JSON輸出

{ 
    "repositories": [ 
    { 
    "id": "156c48fc-f208-43e8-a631-4d12deb89fa4", 
    "namespace": "rhel12", 
    "namespaceType": "organization", 
    "name": "rhel6.6", 
    "shortDescription": "", 
    "visibility": "public" 
    }, 
    { 
    "id": "f359b5d2-cb3a-4bb3-8aff-d879d51f1a04", 
    "namespace": "rhel12", 
    "namespaceType": "organization", 
    "name": "rhel7", 
    "shortDescription": "", 
    "visibility": "public" 
    } 
    ] 
} 

我想在一個新的生產線只有name值與他們每個人的,這樣我可以使用while read -r line。 我只需要

rhel6.6 
rhel7 

我使用JQ如下這似乎不工作:

jq -r '.[].name' 

請建議正確使用JQ這裏

回答

4

您需要通過手段來合併過濾器|運營商:

$ jq -r '.[] | .[] | .name' test.json 
rhel6.6 
rhel7 

第一個.[]取數repositories數組。接下來的.[]獲取repositories數組的所有項。最後,.name從數組項目(對象)中提取屬性。

注意,第一.[]作品的對象,因爲它是一個記錄的功能:

.[] 
    If you use the .[index] syntax, but omit the index entirely, it 
    will return all of the elements of an array... 

    You can also use this on an object, and it will return all the 
    values of the object. 
+0

感謝您的答覆。你可以請我怎樣才能得到輸出格式'rhel12/rhel6.6'換句話說,我需要格式'命名空間/名稱的O/P' – meallhour

+0

@meallhour,'jq -r'。 。[] | [.namespace,.name] |加入(「/」)'test.json' –

6

你想在倉庫陣列尋找治療的輸入作爲一個數組,而不是:

$ jq -r '.repositories[].name' file 
rhel6.6 
rhel7 
+0

感謝您的回覆。你能請我怎樣才能得到輸出格式'rhel12/rhel6.6'換句話說,我需要O/P格式'命名空間/名稱' – meallhour

+2

請單獨發佈新的問題。 –

0

這是另一種解決方案。假設的要求

我想獲得只有名稱值與他們每個人在一個新的行,以便我可以在讀取-r行時使用。

可以請你怎樣才能在格式rhel12輸出/ rhel6.6換句話說,我需要的格式命名空間/ O/P名

如果數據是在data.json則命令

jq -M -r '.repositories[] | "\(.namespace)/\(.name)"' data.json 

應該產生

rhel12/rhel6.6 
rhel12/rhel7