Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ColdFusion: how to check whether JSON property is null?

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 --->
like image 313
Johnny Oshika Avatar asked Mar 24 '14 18:03

Johnny Oshika


People also ask

How do I check if a JSON is null?

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.

Can a JSON property be null?

Null valuesJSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

Is null in ColdFusion?

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.

Is null valid value in JSON?

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


1 Answers

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)

enter image description here

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'
like image 83
Henry Avatar answered Nov 15 '22 09:11

Henry