Reading in JavaScript Object Notation Formatted Data from Text Values or from a File

This tutorial will teach you how to read in JavaScript Object Notation (JSON) formatted data from a text value or from a file

Overview

If you have data which is already in JavaScript Object Notation format, with { “name” : value } pairs in curly braces, then the data can be read in and stored as a JavaScriptObjectNotation object. This data can be read in as a text value or from a file.

Reading in from a Text Value

In this example, we are using the JavaScript Object Notation formatted text “myValue” with the key name “data” and its associated array value.

use Libraries.Data.Formats.JavaScriptObjectNotation

class Main
   action Main
        //sets myValue = {“data” : [21.5, 22.7, 23.9]} 
       text dq = ""
       dq = dq:GetDoubleQuote()
       text myValue = "{" + dq + "data" + dq + ": [21.5, 22.7, 23.9]}"
        //creates a JavaScriptObjectNotation object “json” to store
        //“myValue” and outputs the JavaScript Object Notation formatted object
       JavaScriptObjectNotation json
       json:Read(myValue)
       output json:ToText()
   end
end

The output should look like this:

{
       "data" : [21.5, 22.7, 23.9]
}

Reading in from a File

To read in formatted JavaScript Object Notation data from a file we need to use the additional “Libraries.System.File” library and connect to the file containing the data. The file response.json is available for you to download for testing in this next example.

use Libraries.Data.Formats.JavaScriptObjectNotation
use Libraries.System.File

class Main
   action Main
       JavaScriptObjectNotation json
        //Creates a File object “myFile”, Sets the Path for “myFile”
        //(where you will be reading the JavaScript Object Notation data from)
        //and Reads from the specified file path.
       File myFile
        //be sure to use the file path that you have set your response.json file to
       myFile:SetPath("files/data/response.json")
       json:Read(myFile)
       output json:ToText()
   end
end

Since the file" response.json" that we are reading in from contained the following JavaScript Object Notation formatted data:

{
      "item1": 22,
      "item2": 33.2,
      "item3": true
}

The output to the screen should look like this:

{
      "item1": 22,
      "item2": 33.2,
      "item3": true
}

Next Tutorial

In the next tutorial, we will discuss Writing JavaScript Object Notation Data Overview, which describes how to write JavaScript Object Notation (JSON) formatted data as a text value or to a file.