Tutorial: Adding an Array Value Type to a JavaScriptObjectNotation Object
This tutorial tells you how to add an array value to a JavaScriptObjectNotation (JSON) objectAdding an Array Value Type to a JavaScriptObjectNotation Object
In this tutorial we will create an array using JavaScriptObjectNotation which we will call “array.” We will use "array" as a corresponding value for the key name “detail” in a JavaScriptObjectNotation object called “json.” We will then output the final result. We begin by adding the necessary JavaScriptObjectNotation library and creating our JavaScriptObjectNotation object "array" to be used as a value in our JavaScriptObjectNotation object "json".
use Libraries.Data.Formats.JavaScriptObjectNotation
class Main
action Main
//creates a JavaScriptObjectNotation object "array"
JavaScriptObjectNotation array
//sets the JavaScriptObjectNotation object "array" to type Array.
array:SetArray()
//Adds the values of "project1" and "project2" to "array"
array:Add("arrayValue1")
array:Add("arrayValue2")
Finally, we need to “Add” the JavaScriptObjectNotation object value “array” to the JavaScriptObjectNotation object “json”.
JavaScriptObjectNotation json
json:Add("data1", 10)
json:Add("data2", 11)
json:Add("myArray", array)
Here is the complete code section which will add an array value to a JavaScriptObjectNotation object and output the { name : value } pairs in JavaScript Object Notation format.
use Libraries.Data.Formats.JavaScriptObjectNotation
class Main
action Main
JavaScriptObjectNotation array
array:SetArray()
array:Add("arrayValue1")
array:Add("arrayValue2")
JavaScriptObjectNotation json
json:Add("data1", 10)
json:Add("data2", 11)
json:Add("myArray", array)
json:SetPrettyPrint(true)
output json:ToText()
end
end
The final result should look like this, with the “array” values separated by commas and enclosed within square brackets:
{
"data1": 10,
"data2": 11,
"myArray": ["arrayValue1", "arrayValue2"]
}
Next Tutorial
In the next tutorial, we will discuss Reading JavaScript Object Notation Data Overview, which describes an overview into reading in JavaScript Object Notation (JSON) data from text values and files.