英文:
How to validate fields with if conditional in jq?
问题
我正在验证一个JSON文件,我需要验证一个字段,如果它为空,就赋予一个默认值,我找不到如何使用条件语句进行验证。
file.json
{  
    "timeout": 100
}
jq -r .timeout file.json
在这里,它正确地打印出该值,我需要验证这个字段是否为空,然后使用jq为其赋予一个默认值。
提前感谢。
英文:
I am validating a json file, I need to validate in a field that if it is null, assign a default value, I can't find how to perform a validation with if conditional
file.json
{  
    "timeout": 100
}
jq -r .timeout fiile.json
here it prints the value correctly, I need to validate if this field is null to assign it a default value with jq
Thanks in advance
答案1
得分: 1
使用更新运算符 |= 来更新所讨论的字段。对于条件,只需与 null 进行比较。
jq '.timeout |= if . == null then 200 else . end'
如果你的输入文件是
{  
  "timeout": 100
}
它将保持不变,因为 .timeout 不是 null。但如果它是
{  
  "timeout": null
}
那么它将被更改为给定的默认值,这里是:
{  
  "timeout": 200
}
请注意,这仅对 null 的内容触发。还有其他方法来测试 false、数字零 0、空字符串 "" 等,甚至是该字段的完全缺失。
英文:
Use the update operator |= to update the field in question. For the conditional just compare to null.
jq '.timeout |= if . == null then 200 else . end'
If your input file is
{  
  "timeout": 100
}
it will stay the same, as .timeout is not null. But if it is
{  
  "timeout": null
}
then it will be changed to the default value given, here:
{  
  "timeout": 200
}
Note that this only triggers for the content of null. There are other means to test for false, the number zero 0, the empty string "", etc., even the complete absence of that field.
答案2
得分: 0
你可以尝试替代运算符 //。
英文:
You can try alternative operator //
jq '.timeout //= 200' file.json
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论