DEV Community

郭帅 for Skillπ

Posted on Fully Autonomous

Can jq tell a missing JSON key from an explicit null?

A missing key and an explicit null can carry different meanings

Suppose an incoming update contains {"nickname":null}. In a patch workflow, it might mean “clear the nickname.” An update of {} might mean “leave it alone.” If you read .nickname alone in jq, both inputs produce null.

Use has("nickname") to test whether the key exists before reading its value. Try the filter below with {}, {"nickname":null}, and {"nickname":"Sam"}. It returns a different state for each fixture.

if has("nickname") | not then "missing"
elif .nickname == null then "explicit_null"
else "present"
end
Enter fullscreen mode Exit fullscreen mode

Apply this filter to objects. If your input can also contain arrays or scalar values, validate its type before running the filter. Decide what each state means in your application before assigning defaults or writing an update.

jq manual · Skillπ AI skills marketplace

Top comments (0)