How can i handle boolean JSON in IRIS?
Hi folks!
How can we handle JSON boolean types in IRIS?
I'm having a UI sending me a JSON payload as:
{
"id": 1,
"strprop": "string",
"boolprop": true
}The class is
MyPackage.MyClass Extends (%Persistent, %JSON.Adaptor)
{
strprop as%String;
boolprop as%Boolean;
}And I'm trying to update an instance of a MyPackage.MyClass and I'm getting a datatype-related error, something like %JSONImportInternal+269...
How am I supposed to deal with booleans in JSON with IRIS and ObjectScript? Any best practice advices?
Comments
InterSystems IRIS handles JSON boolean values (true and false) differently than JSON. In ObjectScript, boolean values are represented as integers: 1 for true and 0 for false[1].
To correctly work with a boolean value from JSON, the following practices are recommended:
Conversion During Object Interactions: When defining an object in JSON, you can set properties as
"true"or"false"without issue, which will represent these values properly in a JavaScript JSON context. However, IRIS will convert these values to1or0when interacting via ObjectScript.Setting Boolean Values: If you manually set properties for an object using dot syntax in ObjectScript, you must use
1or0fortrueandfalse, respectively, as IRIS will throw a syntax error for direct use of"true"or"false"outside the dynamic JSON context.Best Practice with
%SetMethod: Use the%Set()method to ensure the type of the values being set. You can specifically set a JSON boolean type by providing its correspondingtypeparameter as"boolean":Set obj.%Set("key", 1, "boolean") ; Sets key to `true` Set obj.%Set("key", 0, "boolean") ; Sets key to `false`
These approaches ensure compatibility and prevent errors when handling JSON boolean values in IRIS [1].
Sources:
Write the id property into your objectscript class, the boolean it is ok
Class MyPackage.MyClass Extends (%Persistent, %JSON.Adaptor)
{
Property JSONid As%Integer(%JSONFIELDNAME = "id");Property strprop As%String;Property boolprop As%Boolean;
}
next this worked
set jsn={ "id": 1, "strprop": "string", "boolprop": true }
set sc=obj.%JSONImport(jsn)
zw obj
+----------------- general information ---------------
| oref value: 2
| class name: MyPackage.MyClass
| reference count: 1
+----------------- attribute values ------------------
| %Concurrency = 1 <Set>
| JSONid = 1
| boolprop = 1
| strprop = "string"
+-----------------------------------------------------If your payload is received as a string
set jsn={}.%FromJSON(payload)
write jsn.%Get("boolprop")works without a persistent object
Thank you, @Yuri Marx @Robert Cemper ! Works for me as well - my issue was that JSON.Adapter is case sensitive. if payload comes as:
{ "strprop": "string", "BoolProp": true } error fires (very unreadable). I thought that reason is the boolean value, but turned out it is property naming issue - should 100% match either name in a class description, or special JSON property name clause.