2017-10-19 42 views
2

假設我有以下json。Bash和jq - 找到包含在變量中的一個關鍵字,並更改它的值

{ 
    "userid":334, 

    "Parameters": [ 
     { 
      "ParameterValue": "james", "ParameterKey": "name" 
     }, 
     { 
      "ParameterValue": "22", "ParameterKey": "age" 
     }, 
     { 
      "ParameterValue": "belfast", "ParameterKey": "city" 
     }, 
     { 
      "ParameterValue": "software", "ParameterKey": "career" 
     } 
    ] 
} 

我有一些代碼需要JSON並提取所有的鍵和它們的值。

echo $my_json | jq -r '.Parameters[] | .ParameterKey + "=" + .ParameterValue' >> $OUTPUT_FILE 

如果我看着我的輸出文件我也有類似這樣:

name=james 
age=22 
city=belfast 
career=software 

我如何才能找到,說「事業」,並改變它的值,它被放置在$ OUTPUT_FILE過嗎?實施例下面:

name=james 
age=22 
city=belfast 
career=consultation 

回答

2

JQ溶液:

echo $my_json | jq -r --arg career "consultation" '.Parameters[] 
    | [.ParameterKey, if (.ParameterKey == "career") then $career else .ParameterValue end] 
    | join("=")' > outputfile 
  • --arg career "consultation" - 傳遞值"consultation"JQ腳本作爲命名一個預定義的變量$career

  • join("=") - 加入/內爆使用=作爲分隔


outputfile內容:

name=james 
age=22 
city=belfast 
career=consultation 
+0

謝謝!你知道我會如何改變這一點,如果ParameterValue爲空,那麼在行的開頭添加'#'? – Xenidious

+0

@ Xenidious,在行首開頭加上'#'是什麼意思*?說明它在特定情況下的外觀 – RomanPerekhrest

2

可以使用map()功能:

jq -r '.Parameters | map(
      if .ParameterKey == "career" then (.ParameterValue = "foo") else . end) 
     [] | .ParameterKey + "=" + .ParameterValue' 
1

這是該解決方案使用from_entries 的泛化來將數據轉換爲中間對象,object multiplication with *以更新所需的鍵以及考慮空白值來格式化輸出的功能。

首先,我們假設JQ將與--argjson參數被調用如下指定鍵被替換:

$ jq -Mr --argjson replace '{"career":"consultation"}' -f filter.jq data.json 

其中data.json包含樣品數據和filter.jq包含以下濾波器:

def from_entries(k;v): map({(k):v})|add; 
def format_output:  keys[] as $k | if .[$k]!="" then "\($k)=\(.[$k])" else "#\($k)=" end; 

    .Parameters 
| from_entries(.ParameterKey;.ParameterValue) 
| . * $replace 
| format_output 

取樣輸出:

age=22 
career=consultation 
city=belfast 
name=james 

相反,如果我們運行它

$ jq -Mr --argjson replace '{"career":""}' -f filter.jq data.json 

輸出是

age=22 
#career= 
city=belfast 
name=james 

Try it online!

相關問題