簡體   English   中英

Bash和jq-查找包含在變量中的鍵並更改其值

[英]Bash and jq - Find a key contained in a variable and change it's value

假設我有以下json。

{
    "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

您可以使用map()函數:

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

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"作為名為$career的預定義變量傳遞到jq腳本中

  • join("=") -使用=作為分隔符連接/插入


outputfile內容:

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

這是一個解決方案,它使用from_entries的泛型將數據轉換為中間對象, 使用*進行對象乘法以更新所需的鍵,並使用函數考慮空白值來格式化輸出。

首先,我們假設將使用--argjson參數調用jq,如下所示以指定要替換的密鑰:

$ 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

在線嘗試!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM