Bash和jq - 找到包含在变量中的一个关键字,并更改它的值

问题描述:

假设我有以下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 

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

可以使用map()功能:

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

这是该解决方案使用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!