skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. You can try alternative operator //

    jq '.timeout //= 200' file.json
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search