【问题标题】:jq compilation error for two maps - not replacing json value两个地图的 jq 编译错误 - 不替换 json 值
【发布时间】:2017-11-20 01:50:12
【问题描述】:

在 shell 脚本中使用两个 jq 映射时,我发现以下数据出现错误。

test.json

[
  {
     "ParameterKey": "<ans1>",
     "ParameterValue": "<ans2>"
  }
]

我的脚本是

cat test.json | \
jq 'map(if .ParameterKey == "<ans1>" then . + {"ParameterKey" : "input1" } else . end )' \
   'map(if .ParameterValue == "<ans2>" then . + {"ParameterValue" : "input2" } else . end)' \ 
> result.json

【问题讨论】:

    标签: json jq


    【解决方案1】:

    这里有两种解决方案 - 一种既简单又简短,另一种可以很好地扩展。请注意,在这两种情况下,map 只需要一次。

    简单明了

    map( if .ParameterKey   == "<ans1>" then . + {"ParameterKey":   "input1"} else . end
       | if .ParameterValue == "<ans2>" then . + {"ParameterValue": "input2"} else . end)
    

    带有辅助函数

    def maybe_update($key; $old; $new):
      if .[$key] == $old then .[$key] = $new else . end;
    
    map( maybe_update("ParameterKey";   "<ans1>"; "input1")
       | maybe_update("ParameterValue"; "<ans2>"; "input2") )
    

    【讨论】:

      【解决方案2】:

      虽然没有给出准确的错误,但运行命令会生成

      jq: error: Could not open file map(if .ParameterValue == "<ans2>" 
      then . + {"ParameterValue": "input2"} else . end): No such file or directory
      

      No such file or directory 消息表明 jq 正在尝试打开文件 命名为 "map(if .ParameterValue == "&lt;ans2&gt;" then . + {"ParameterValue": "input2"} else . end)" 发生这种情况是因为该字符串出现在 jq 期望输入文件名称的位置。

      要更正此问题,您可以将两个过滤器字符串与| 合并为一个字符串,并将test.json 作为输入文件传递,例如

      jq '
         map(if .ParameterKey == "<ans1>" then . + {"ParameterKey": "input1"} else . end)
       | map(if .ParameterValue == "<ans2>" then . + {"ParameterValue": "input2"} else . end)
      ' test.json > result.json
      

      或保留您的基本结构并添加第二个显式 jq 调用,例如

      cat test.json | \
      jq 'map(if .ParameterKey == "<ans1>" then . + {"ParameterKey": "input1"} else . end)' | \
      jq 'map(if .ParameterValue == "<ans2>" then . + {"ParameterValue": "input2"} else . end)' \
      > result.json
      

      在这种特殊情况下,两种方法都可以,但第一种方法更有效。 Peak's suggestion 只使用一个 map() 更好。

      【讨论】:

        猜你喜欢
        • 2020-12-28
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        • 2018-08-17
        • 2016-12-30
        • 2020-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多