Leonardo Arango
Leonardo Arango

Reputation: 67

How to validate fields with if conditional in 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

Upvotes: 0

Views: 101

Answers (2)

Philippe
Philippe

Reputation: 26850

You can try alternative operator //

jq '.timeout //= 200' file.json

Upvotes: 0

pmf
pmf

Reputation: 36601

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.

Upvotes: 1

Related Questions