Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json Bash和jq-找到变量中包含的键并对其进行更改';s值_Json_Bash_Jq - Fatal编程技术网

Json Bash和jq-找到变量中包含的键并对其进行更改';s值

Json Bash和jq-找到变量中包含的键并对其进行更改';s值,json,bash,jq,Json,Bash,Jq,假设我有以下json { "userid":334, "Parameters": [ { "ParameterValue": "james", "ParameterKey": "name" }, { "ParameterValue": "22", "ParameterKey": "age" }, { "ParameterV

假设我有以下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_文件之前,我如何查找(比如说“职业”)并更改其值?示例如下:

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

下面是一个解决方案,它使用 将数据转换为中间对象、更新所需的键以及设置输出格式(考虑空白值)的函数

首先,我们假设将使用如下参数调用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

谢谢!你知道如果参数值为空,我将如何将其更改为ammend a'#'作为行的开头吗?@Xenidious,将ammend a'#'作为行的开头意味着什么?展示它在特定情况下的外观