Tutorial: Adding a JavaScriptObjectNotation Value Type to a JavaScriptObjectNotation Object (Nesting)

This tutorial tells you how to nest JavaScriptObjectNotation object values within a JavaScriptObjectNotation object

Nesting

In this tutorial, we will create a JavaScriptObjectNotation object “data” which will be nested in another JavaScriptObjectNotation object “json” and then output the final result. We begin by creating the JavaScriptObjectNotation object that we plan on nesting, “data” and “Add”ing the necessary { name : value } pairs to the nested JavaScriptObjectNotation object “data.”

use Libraries.Data.Formats.JavaScriptObjectNotation

class Main
   action Main
       JavaScriptObjectNotation data
       data:Add("item1", "a")
       data:Add("item2", "b")
       data:Add("item3", "c")

We then create the JavaScriptObjectNotation object, which will encapsulate the nested object, “json” and “Add” the necessary { name : value } pairs. To add the JavaScriptObjectNotation object to a { name : value } pair we change the value to the object to be nested, in this case “data.”

     json:Add("detail", data)

Here is the complete code section which will create a nested JavaScriptObjectNotation object and output the formatted JavaScriptObjectNotation objects.

use Libraries.Data.Formats.JavaScriptObjectNotation

class Main
   action Main
       JavaScriptObjectNotation data
       data:Add("item1", "a")
       data:Add("item2", "b")
       data:Add("item3", "c")

       JavaScriptObjectNotation json
       json:Add("data1", "A")
       json:Add("data2", "B")
       json:Add("detail", data)
       output json:ToText()
   end
end

The output should look something like this, with the nested JavaScriptObjectNotation object enclosed by an inner pair of curly braces following its corresponding key name “detail”:

{
   "data1": "A",
   "data2": "B",
   "detail":   {
           "item1": "a",
           "item2": "b",
           "item3": "c"
   }
}

Next Tutorial

In the next tutorial, we will discuss JavaScript Object Notation Using Arrays, which describes how to use array values with JavaScriptObjectNotation objects.