Let's say I POST this simple JSON payload:
{"foo":null}
On the ColdFusion server, how do I check if the 'foo' property is null?
IsDefined won't work because it will be false for null values. IsNull won't work because IsNull will be true for not just null values, but also for missing properties.
<cfset json = DeserializeJSON(GetHttpRequestData().content) />
<cfdump var="#IsDefined("json.foo")#" /> <!--- false --->
<cfdump var="#IsNull(json.foo)#" /> <!--- true --->
<cfdump var="#IsNull(json.bar)#" /> <!--- true --->
To check null in JavaScript, use triple equals operator(===) or Object is() method. If you want to use Object.is() method then you two arguments. 1) Pass your variable value with a null value. 2) The null value itself.
Null valuesJSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
Previously, the output of isNull function was a reverse of the output of isDefined function, but now it checks for a variable with value null. Note: Null is a reserved keyword in ColdFusion. You will not be allowed to create a variable named “null” in your application.
One of the changes in RFC 7159 is that a JSON text is not defined as being an object or an array anymore but rather as being a serialized value. This means that with RFC 7159, “null” (as well as “true” and “false”) becomes a valid JSON text. So the JSON text serialized value of a null object is indeed “null”.
My mistake, I thought null
in JSON would be deserialized to empty string, but it's not true.
null
in JSON is translated to be struct with key foo
but undefined in CF10. (not sure about older CF version)
Therefore, a true isStructValueNull()
can be written like this:
function isStructValueNull(struct, key) {
return listFind(structKeyList(struct), key)
&& !structKeyExists(struct, key);
}
json = deserializeJSON('{"foo":null,"bar":123}');
writeDump(isStructValueNull(json, "foo")); // yes
writeDump(isStructValueNull(json, "bar")); // no
or you can loop through json
and use structKeyExists()
, if it's false, it's null.
function structNullKeyList(struct) {
var nulls = "";
for (var key in struct)
if (!structKeyExists(struct, key))
nulls = listAppend(nulls, key);
return nulls;
}
writeDump(structNullKeyList(json)); // 'foo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With