Question
· Dec 12, 2023

JSONImporting an array without a key

I'm receiving a JSON payload via a REST API, I'd like to %JSONImport this stream into a class which extends %JSON.Adaptor. The problem is that the JSON is an array whose elements have no key (as you can see in the example JSON below). Right now I'm having to do some manipulations to convert the stream into a dynamic object and do a %Set which inserts a made up key "record" so "thingone" and "thingtwo" have an associated key that I can use when referencing "thingone" and "thingtwo"...such as record.GetAt(1).thingone

I'm also finding myself having to do the reverse when sending payloads back out and removing "record". Is there a way I can build my class so I don't have to do those manipulations? Or is there just a better way?

 

Below is how the JSON comes in from the remote system.

[
    {
        "thingone": "Red",
        "thingtwo": "Green"
    },
    {
        "thingone": "Blue",
        "thingtwo": "Yellow"
    }
]
$ZV: IRIS for UNIX (Red Hat Enterprise Linux for x86-64) 2021.1.2 (Build 338_0_21969U) Mon Oct 24 2022 14:54:48 EDT
Discussion (3)1
Log in or sign up to continue
Class DC.Import Extends (%Persistent, %JSON.Adaptor)
{

Property thingone As %String;
Property thingtwo As %String;
ClassMethod Test()
{
	// create a test stream
	set myStream=##class(%Stream.TmpCharacter).%New()
	do myStream.Write("[{""thingone"":""Red"",""thingtwo"":""Green""},{""thingone"":""Blue"",""thingtwo"":""Yellow""}]")
	
	// convert input (JSON) stream into a JSON object
	set data={}.%FromJSON(myStream)
	
	// loop over the JSON-Array and import each array element into your database
	for i=0:1:data.%Size()-1 {
		set obj=..%New()
		set sts=obj.%JSONImport(data.%Get(i))
		if sts set sts=obj.%Save()
		if sts continue
		write "Error: i=",i,", reason=",$system.Status.GetOneErrorText(sts),!
	}
}

Of course, instead of "myStream" you should use your REST-input stream.

do ##class(DC.Import).Test()

zwrite ^DC.ImportD
^DC.ImportD=2
^DC.ImportD(1)=$lb("","Red","Green")
^DC.ImportD(2)=$lb("","Blue","Yellow")