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

缺失的键和显式的 null 可能具有不同的含义。假设传入的更新包含 {“nickname”:null}。在补丁工作流中,这可能意味着“清除昵称”。而 {} 的更新可能意味着“保持原样”。

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.

如果你在 jq 中单独读取 .nickname,这两个输入都会产生 null。请在读取值之前使用 has(“nickname”) 来测试该键是否存在。尝试对 {}、{“nickname”:null} 和 {“nickname”:“Sam”} 使用下方的过滤器。它会为每个测试用例返回不同的状态。

if has(“nickname”) | not then “missing” elif .nickname == null then “explicit_null” else “present” end

if has(“nickname”) | not then “missing” elif .nickname == null then “explicit_null” else “present” end

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.

将此过滤器应用于对象。如果你的输入还可能包含数组或标量值,请在运行过滤器之前验证其类型。在分配默认值或编写更新之前,请确定每种状态在你的应用程序中代表什么含义。