ColdFusion: how to check if the JSON property is zero?

Let's say I DID this simple JSON payload:

{"foo":null}

On a ColdFusion server, how to check if the 'foo' property is null?

IsDefined will not work because it will be false for null values. IsNull will not work because IsNull will be true for not only 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 --->
+4
source share
4 answers

My mistake, I thought that nullin JSON it would be deserialized for an empty string, but it is not.

null JSON foo, undefined CF10. ( CF)

enter image description here

, isStructValueNull() :

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

json structKeyExists(), , 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'
+11

? , "json"?

ColdFusion, scope. HTTP POST, , .

, <cfif structKeyExists(form, "foo")>, , form.foo . (ColdFusion NULL .)

0

Raillo.

Railo 4.1.3.005 () [FOO] NULL, CFML.

Full Null suport. , , .

<cfscript>

    objectValues = { 'one' : 1 , 'two' : 2 , 'three' : JavaCast( "null", 0 ) , 'four' : null };

    dump(objectValues);

    // Known existing attribute
    dump('three');
    dump( isDefined('objectValues.three') );
    dump( isNull(objectValues.three) );
    dump( StructKeyExists(objectValues,'three') );

    // Known Railo Null value
    dump('four');
    dump( isDefined('objectValues.four') );
    dump( isNull(objectValues.four) );
    dump( StructKeyExists(objectValues,'four') );

    // Unknown existing attribute
    dump('five');
    dump( isDefined('objectValues.five') );
    dump( isNull(objectValues.five) );
    dump( StructKeyExists(objectValues,'five') );

</cfscript>

ColdFusion?

0

JSON null "null" Coldfusion, ,

:

<cfset s = StructNew()>
<cfset s.test = "" />
<cfset json = SerializeJSON(s)>
<cfdump var="#json#">
<cfset d = DeserializeJSON(json)>
<cfdump var="#d#">

json: { "TEST": ""} d.test - ""

null :

<cfset s = StructNew()>
<cfset s.test = javaCast( "null", "" ) />
<cfset json = serializeJSON(s)>
<cfdump var="#json#">
<cfset d = DeserializeJSON(json)>
<cfdump var="#d#">

json: { "TEST": null} d.test - "null"

This is probably more preferable if you can do this:

<cfif StructKeyExists(d,"TEST") AND Compare(d.test,"null") IS 0>
0
source

Source: https://habr.com/ru/post/1533210/


All Articles