Superseded on 2023-04-17.
To create json in D3, I have 3 functions. JSON.ADD, JSON.CREATE.OBJECT and JSON.CREATE.ARRAY.
JSON.ADD creates a key value pair. In D3, this will simply add an attribute to a dynamic array containing our key and value.
SUBROUTINE JSON.ADD(BUFFER,KEY,VALUE)
*
IF BUFFER = '' THEN
BUFFER = KEY : @VM : VALUE
END ELSE
BUFFER = BUFFER : @AM : KEY : @VM : VALUE
END
*
RETURN
*
* END OF PROGRAM
*
END
*
The next function is the JSON.CREATE.OBJECT function. This has a tiny bit of logic to handle things.
SUBROUTINE JSON.CREATE.OBJECT(JSON,BUFFER)
*
NUMBER.OF.KEYS = DCOUNT(BUFFER,@AM)
JSON = ''
*
FOR I = 1 TO NUMBER.OF.KEYS
KEY = TRIM(BUFFER<I,1>)
VALUE = TRIM(BUFFER<I,2>)
*
IF VALUE # '' AND (VALUE[1,1] = '[' OR VALUE[1,1] = '{' OR NUM(VALUE)) THEN
JSON<-1> = '"' : KEY : '": ' : VALUE
*
END ELSE
KEY = CHANGE(KEY,'"','\"')
VALUE = CHANGE(VALUE,'"','\"')
*
JSON<-1> = '"' : KEY : '": "' : VALUE : '"'
END
NEXT I
*
CONVERT @AM TO ',' IN JSON
JSON = '{ ' : JSON : ' }'
*
RETURN
*
* END OF PROGRAM
*
END
*
Here I check if the value is blank, if it is blank, then it will give an empty string. If the value starts with a '[' or a '{', then I'm assuming the string has already been converted to a json array or a json object.
Special Note You cannot use square or curly brackets as a starting character for a json value.
The last function is the JSON.CREATE.ARRAY function:
SUBROUTINE JSON.CREATE.ARRAY(JSON.ARRAY,BUFFER)
*
CONVERT @AM TO ',' IN BUFFER
JSON.ARRAY = '[' : BUFFER : ']'
*
RETURN
*
With that we have a set of functions that can generate json easily.