简体   繁体   English

使用 JQ 搜索多个键:值对并已替换为定义变量

[英]With JQ search multiple key: value pairs and replace with define variable already

I have a couple of json files and both or one of the keys below, might exist or none exists.我有几个 json 文件和下面的两个或一个键,可能存在或不存在。

{
  "parent1": {
    "parent1key": "parent1value"
  },
  "parent2": {
    "parent2key": "parent2value"
  }

}

if both the key: pairs always exist, I could use如果两个 key: 对总是存在,我可以使用

jq --arg parent1keyarg $MyVAL1 --arg parent2keyarg $MyVAL2 '(..|objects|select(.parent1key ).parent1key ) |= $parent1keyarg | (..|objects|select(.parent2key).parent2key) |= $parent2keyarg ' jsonfile.json

  1. I want to find the parent1key and parent2key and if found one or both, then replace them with a variable that's generated during runtime.我想找到parent1keyparent2key ,如果找到一个或两个,然后用运行时生成的变量替换它们。 If none of the key: values are found just ignore it rather than troughing up an error.如果没有找到 key: 值,则忽略它而不是遇到错误。

  2. I want to use jq --arg instead of bash if conditions, just to ensure the JSON formatting is accurate ( or jq is interesting to me ).我想使用jq --arg而不是 bash if条件,只是为了确保 JSON 格式准确(或者 jq 对我来说很有趣)。

how could we write conditions in JQ is what I'm unable to figure out from jq manuals.我们如何在 JQ 中编写条件是我无法从 jq 手册中弄清楚的。

Appreciate it if anyone could help me with this.如果有人可以帮助我,我将不胜感激。

Thanks!谢谢!

From your description, it would seem the following would suffice:根据您的描述,以下内容似乎就足够了:

if has("parent1key") then .parent1key = $a
else . end 
| if has("parent2key") then .parent2key = $b
  else . end

If you need more than that, then I'd use the above with walk :如果你需要更多,那么我会使用上面的walk

walk(if type=="object"
     then if has("parent1key") then .parent1key = $a
          else . end 
          | if has("parent2key") then .parent2key = $b
            else . end
     else . end)

A simple walk/1 expression would be sufficient to check for existence of the key recursively.一个简单的walk/1表达式就足以递归地检查密钥是否存在。 It can be further improved by making it a function.它可以通过使其成为一个功能来进一步改进。

def replace(k; v):
   walk(if type == "object" and has(k) then .[k] = v else . end);

replace("parent1key"; "foo") | replace("parent2key"; "bar")

The first argument to replace takes the key name for which the value is to be replaced. replace 的第一个参数采用要replace其值的键名。 Simply pipe any numbers of keys and the associated values that you want to change.只需通过管道传输任意数量的键和您想要更改的关联值。

( .parent1.parent1key | select( . ) ) |= $parent1keyarg |
( .parent2.parent2key | select( . ) ) |= $parent2keyarg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM