Question
· 12 hr ago

Building a dynamic Object: how can I use variables?

Hi developers!

In a method I need to return a result as a dynamic object aka JSON Object. And here is my logic:

Classmethod Planets() as %DynamicObject {

 set val1="Jupiter"

 set val2="Mars"

// this doesn't work! cannot compile

 return {"value1":val1, "value2":val2}

}

So I need to do the following:

Classmethod Planets() as %DynamicObject {

 set val1="Jupiter"

 set val2="Mars"

 set result={}

 set result.value1=val1

 set result.value2=val2

 return result

}

The second case works. Maybe I'm preparing the Dynamic Object in the wrong way? Can we just use variables inside JSON? Or should I create an object and initialize it manually?

Could you share your experience with it, please?

Product version: IRIS 2025.3
Discussion (6)2
Log in or sign up to continue

In InterSystems IRIS, the construction and manipulation of dynamic objects like JSON objects can be achieved in various ways using the %DynamicObject class.

Issue with Direct JSON Syntax Incorporating Variables

When attempting return {"value1":val1, "value2":val2}, you are utilizing JSON literal syntax directly with variables. This won't work because ObjectScript does not dynamically interpret variables within such JSON literals. Instead, it requires an explicit declaration or assignment for each field.

Correct Dynamic Object Construction

For initializing dynamic objects with variables, you need to use step-by-step assignment. Below is an example:

ClassMethod Planets() As %DynamicObject
{
    Set val1 = "Jupiter"
    Set val2 = "Mars"
    Set result = {}
    Set result.value1 = val1
    Set result.value2 = val2
    Return result
}

This approach builds the dynamic object incrementally and ensures compatibility.

Alternative Using %DynamicObject Methods

The %DynamicObject class provides built-in methods like Set to explicitly set fields in the object. This method allows specifying both the key and value dynamically:

Set json = {}
Do json.%Set("value1", val1)
Do json.%Set("value2", val2)
Return json

Both approaches work because the dynamic object understands individual assignments and ensures proper serialization to JSON format. This clarifies that within ObjectScript, variables must be individually assigned to object properties rather than being interpreted directly in literal JSON syntax [1].

Sources: