2016-09-28 66 views
2

這是我的對象的JSON數組看起來像JSON對象:遍歷使用JQ

[ 
    { 
     "Description": "Description 1", 
     "OutputKey": "OutputKey 1", 
     "OutputValue": "OutputValue 1" 
    }, 
    { 
     "Description": "Description 2", 
     "OutputKey": "OutputKey 2", 
     "OutputValue": "OutputValue 2" 
    }, 
    { 
     "Description": "Description 3", 
     "OutputKey": "OutputKey 3", 
     "OutputValue": "OutputValue 3" 
    }, 
    { 
     "Description": "Description 4", 
     "OutputKey": "OutputKey 4", 
     "OutputValue": "OutputValue 4" 
    }, 
    { 
     "Description": "Description 5", 
     "OutputKey": "OutputKey 5", 
     "OutputValue": "OutputValue 5" 
    }, 
    { 
     "Description": "Description 6", 
     "OutputKey": "OutputKey 6", 
     "OutputValue": "OutputValue 6" 
    } 
] 

我如何遍歷這個使用JQ,使我可以在其他命令OutputKey和OutputValue的價值?

+0

@tripleee,作爲其他問題接受答案的作者,我選擇了單獨回答這個問題,因爲重讀這個問題的答案,我不認爲這是在這裏特別有用/適用 - 它花費了太多的時間在「雜草」中,OP做錯了什麼,還沒有提供一個普遍適用的良好實踐。事實上,它假設OP已經知道jq,並且嚴格地關注bash的結束 - 並沒有提供關於如何實際遍歷數組的指導。 –

+0

@tripleee,......老實說,如果有空間把另一個作爲另一個的副本來關閉,我幾乎會試圖關閉這個作爲這個的副本,因爲這裏的答案更可能對其他人有用(並且這裏的問題以一種有利於這種答案的方式被詢問,而沒有需要一系列指導/修正的事先實施)。 –

+0

@tripleee,...我已經更新了另一個問題,以更好地反映它的(不是特別可概括的)內容的標題。 –

回答

6

假設您的內容是從in.json來:

#!/usr/bin/env bash 
case $BASH_VERSION in (""|[123].*) echo "Bash 4.0 or newer required" >&2; exit 1;; esac 

declare -A values=() descriptions=() 

while IFS= read -r description && 
     IFS= read -r key && 
     IFS= read -r value; do 
    values[$key]=$value 
    descriptions[$key]=$description 
    echo "Read key $key, with value $value and description $description" >&2 
done < <(jq -r '.[] | (.Description, .OutputKey, .OutputValue)' <in.json) 

鑑於你的輸入,它會產生以下標準錯誤:

Read key OutputKey 1, with value OutputValue 1 and description Description 1 
Read key OutputKey 2, with value OutputValue 2 and description Description 2 
Read key OutputKey 3, with value OutputValue 3 and description Description 3 
Read key OutputKey 4, with value OutputValue 4 and description Description 4 
Read key OutputKey 5, with value OutputValue 5 and description Description 5 
Read key OutputKey 6, with value OutputValue 6 and description Description 6 

而且,運行此代碼後,您可以然後執行:

key_to_look_up="OutputKey 1" 
echo "${values[$key_to_look_up]}" 
echo "${descriptions[$key_to_look_up]}" 

...並獲得儘可能輸出:

OutputValue 1 
Description 1 
+1

請注意'。[] | [.Description,.OutputKey,.OutputValue] | 。[]'可以簡化爲:'。[] | (.Description,.OutputKey,.OutputValue)',甚至可以在這個特殊情況下刪除這些parens。 – peak

+0

好點,謝謝!我認爲這些parens增加了清晰度,所以我會保留它們,但是你實際上幫助我更好地理解了jq的模型。 –

+0

(擺脫不必要的中間數組在每個方面都有所改進 - 更具可讀性,處理開銷更少;再次感謝您)。 –

1
  1. 恐怕你的問題不是很清楚。如果您想通過除jq之外的某個工具或應用程序來生成消費的值,那麼知道該工具期望的內容會很有幫助。如果你想使用jq本身的值,那麼你可以使用mapreduce;或者,可以使用具有以下形式的過濾器:.[] | ...[.[] ...],其中...是訪問感興趣值的一些jq代碼,例如,

    [.[] | [.OutputKey, .OutputValue] ] 
    
  2. 如果要執行一些歸約操作,那麼你可能會想使用形式:reduce .[] as $x (_; _)

  3. 還有其他的選擇,這取決於它是什麼你正在嘗試做的。

+0

我修復了JSON。我試圖在這個數組上運行一個for循環,並獲取我可以傳遞給我在for循環中調用的其他函數的值。我期望得到的值是使用OutputKey。 – Asdfg