Skip to main content

Resolving JSON Null and Boolean Values

Resolving JSON Null and Boolean Values

In JSON syntax, the values true, false, and null are distinct from values 1, 0, and "" (empty string), but ObjectScript does not make this distinction. When JSON values are retrieved from an element or property, they are always cast to ObjectScript-compatible values. This means that JSON true is always returned as 1, false as 0, and null as "". In most cases this will be the desired result, since the return value can be used in an ObjectScript expression without first converting it from JSON format. The dynamic entity retains the original JSON or ObjectScript value internally, so you can use %GetTypeOf() to identify the actual datatype if necessary.

In the following example, the dynamic array constructor specifies JSON true, false, and null values, numeric and string literal values, and ObjectScript dynamic expressions (which evaluate to ObjectScript boolean values 1 and 0):

   set test = [true,1,(1=1),false,0,(1=2),"",null]
   write test.%ToJSON()
[true,1,1,false,0,0,"",null]

As you can see above, the values assigned in the constructor have been preserved in the resulting dynamic array, and are displayed properly when serialized as a JSON string.

The following example retrieves and displays the array values. As expected, JSON values true, false, and null are cast to ObjectScript-compatible values 1, 0, and "":

   set iter = test.%GetIterator()
   while iter.%GetNext(.key,.val){write "/"_val_"/ "}
/1/ /1/ /1/ /0/ /0/ /0/ // //

This example uses %GetNext(), but you would get the same results if you retrieved values with %Get(), %Pop(), or dot syntax.

When necessary, you can use the %GetTypeOf() method to discover the original datatype of the value. For example:

   set iter = test.%GetIterator()
   while iter.%GetNext(.key,.val) {write !,key_": /"_test.%Get(key)_"/ = "_test.%GetTypeOf(key)}
0: /1/ = boolean
1: /1/ = number
2: /1/ = number
3: /0/ = boolean
4: /0/ = number
5: /0/ = number
6: // = string
7: // = null
Note:
Datatypes in Dynamic Objects

Although this chapter concentrates on dynamic arrays, the same datatype conversions apply to dynamic object values. The examples in this section will work exactly the same if dynamic array test is replaced with the following dynamic object:

   set test = {"0":true,"1":1,"2":(1=1),"3":false,"4":0,"5":(1=2),"6":"","7":null}

Except for this line, none of the example code has to be changed. The property names in this object are numeric strings corresponding to the index numbers of the original array, so even the output will be identical.

FeedbackOpens in a new tab