KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Embedding arrays into a JSON object using new 4D v14 commands
PRODUCT: 4D | VERSION: 14.0 | PLATFORM: Mac & Win
Published On: March 3, 2014

4D v14 offers powerful new tools for creating JSON objects that can be used web page Javascrits. For simple JASON objects the use of the v14 Object language and and JSON (JavaScript Object Notation) commands is straight forward. However, when building complex JASON object a little prior planning is necessary.

Consider the need to embed support for a DOM menu object that contains a submenu with a number of choices. The snippet below is an example of the type of prior planning of how to use the tools is needed to build the JSON from the inside out.

The snippet below breaks the process done into five steps.

C_OBJECT($Menu_O;$Items_O;$Ele1_O;$Ele2_O;$Ele3_O)

   // STEP 1) Build the submenu Key-Value pairs
   //
OB SET($Ele1_O;"value";"New";"onClick";"CreateNewDoc()")
OB SET($Ele2_O;"value";"Open";"onClick";"OpenDoc()")
OB SET($Ele3_O;"value";"Close";"onClick";"CloseDoc()")

ARRAY OBJECT($Items_aO;0)

   // STEP 2) Build the array of submenu key items
   // With C_OBJECT declared vars, APPEND TO ARRAY makes
   // use of the 4D Array zero element.
   //
APPEND TO ARRAY($Items_aO;$Ele1_O)
APPEND TO ARRAY($Items_aO;$Ele2_O)
APPEND TO ARRAY($Items_aO;$Ele3_O)

   // STEP 3) Encode the submenu elements into the "$Items_O" object
   //
OB SET ARRAY($Items_O;"Items";$Items_aO)

   // STEP 4) Encode the submenu "$Menu_O" object
   //
OB SET($Menu_O;"Menu";$Items_O)

$JSON_T:=JSON Stringify($Menu_O)

   // STEP 5) Now it can be sent to web page or the Pasteboard
   //
WEB SEND TEXT($JSON_T)
   // or
SET TEXT TO PASTEBOARD($JSON_T)


Of special note is use of the 4D Array element "zero", see the image below. Normally unused, it has a significan role in the production of JSON arrays. Whereas 4D arrays are "1" based, Javascript arrays are "0" based. So the 4D zero element gets used in this process.

Whereas APPEND ARRAY leaves element zero unused, the call to OB SET ARRAY makes use of the zero element because in Javascript arrays are zero based, not one based as in 4D.



The JSON string produced is recognizes in Javascript editors with all the Key-Value pairs and the Validator give a true represtation of the desired structure.