2016-06-14 22 views
0

我使用下面的curl命令:如何使用bash從json中檢索「name」值?

curl -s -v --user admin:orca --insecure -X GET https://insecure.registry.com/api/v0/repositories/authi-api/tags 

獲得以下輸出:

{ 
    "name": "Dev_ReleaseRollout_Lane-3", 
    "inRegistry": true, 
    "hashMismatch": false, 
    "inNotary": false 
    }, 
    { 
    "name": "Dev_ReleaseRollout_Lane-latest", 
    "inRegistry": true, 
    "hashMismatch": false, 
    "inNotary": false 
    }, 
    { 
    "name": "Payments_Dev_Lane-267", 
    "inRegistry": true, 
    "hashMismatch": false, 
    "inNotary": false 
    } 

我想在一個變量中只得到name值。
我只需要在一個變量

+0

到目前爲止您已嘗試過哪些命令,它們輸出了什麼? –

+0

你是否得到一個數組:'[[...]''或上面提到的輸出? – andlrc

回答

0

Dev_ReleaseRollout_Lane-3Dev_ReleaseRollout_Lane-latestPayments_Dev_Lane-267假設你實際上有三個物體周圍的數組:

$ curl ... | jq -r '.[].name' 
Dev_ReleaseRollout_Lane-3 
Dev_ReleaseRollout_Lane-latest 
Payments_Dev_Lane-267 

這是相當簡單的,.是數組,[].name在取名字從每個元素陣列。 -r是原始輸出。

--raw-output/-r:
使用此選項,如果過濾的結果是一個字符串,那麼它將被直接寫入標準輸出,而不是被格式化爲一個JSON字符串引號。這對於使jq過濾器與非基於JSON的系統進行交談非常有用。

如果實際上是爲遵守上述捲曲輸出將工作:

jq -rRs '"[\(.)]" | fromjson[].name' file.json 

不過,我認爲這是一個更好的方式來環繞輸入數組,

-R是原始輸入和-s是slurp。 \(...)string interpolation

--slurp/-s:
相反運行輸入中的每個JSON對象的過濾器的,讀取整個輸入流分成大陣列和運行過濾器一次。