JSON Class

Properties   Methods   Events   Configuration Settings   Errors  

The JSON class can be used to parse and write JSON documents.

Syntax

class ipworks.JSON

Remarks

The JSON class offers a fast and simple way to parse and write information in JSON documents.

Parsing JSON

The JSON class parses JSON documents and verifies that they are well-formed. The results are provided through a set of events.

In addition, the document structure may be queried through an x_path mechanism that supports a subset of the XPath and JSONPath specification.

The parser is optimized for read applications, with a very fast engine that builds internal DOM structures with close to zero heap allocations. Additionally, build_dom can be set to False which reduces the overhead of creating the DOM and offers a fast forward-only parsing implementation which fires events to provide the parsed data.

When parsing a document events will fire to provide information about the parsed data. After parse returns the document may be navigated by setting x_path if build_dom is True (default). If build_dom is False parsed data is only accessible through the events.

The following events will fire during parsing:

If build_dom is True (default), x_path may be set after this method returns. x_path may be set to navigate to specific elements within the JSON document. This will be the path to a specified value within the document. Since arrays in JSON only contain values, and no associated object name, an empty name will be used for these values. To reach an array element at position 1, the path must be set to "[1]". In addition, a root element named "json" will be added to each JSON document in the parser.

build_dom must be set to True prior to parsing the document for the x_path functionality to be available.

The x_path property accepts both XPath and JSONPath formats. Please see notes below on both formats.

XPath

The path is a series of one or more element accessors separated by '/'. The path can be absolute (starting with '/') or relative to the current x_path location.

The following are possible values for an element accessor:

'name'A particular element name.
[i]The i-th subelement of the current element.
..the parent of the current element.

When x_path is set to a valid path the following properties are updated:

build_dom must be set to True prior to parsing the document for the x_path functionality to be available.

Simple JSON document


{
  "firstlevel": {
    "one": "value",
    "two": ["first", "second"],
    "three": "value three"
  }
}
Example (Setting XPath)

Document root JsonControl.XPath = "/"
Specific Element JsonControl.XPath = "/json/firstlevel/one/"
i-th Child JsonControl.XPath = "/json/firstlevel/two/[i]/"

Note: When using XPath notation the root element is always referred to as "json". As in the above examples this means all paths will begin with "/json".

JSONPath

This property implements a subset of the JSONPath notation. This may be set to point to a specific element in the JSON document.

The JSONPath is a series of one or more accessors in either dot-notation

$.store.book[0].title
Or bracket-notation
$['store']['book'][0]['title']

After setting x_path the following properties are populated:

Examples

Given the following JSON document:

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
}
The following code shows several examples.

Get the first book's author:


json.XPath = "$.store.book[0].author";
Console.WriteLine(json.XText);

//Output
//"Nigel Rees"
Select the first book and inspect the children:


json.XPath = "$.store.book[0]";
Console.WriteLine("Child Count: " + json.XChildren.Count);
Console.WriteLine(json.XChildren[1].Name + ": " + json.XChildren[1].XText);

//Output
//Child Count: 4
//author: "Nigel Rees"
Get the price of the second book:


json.XPath = "$['store']['book'][1]['price']";
Console.WriteLine(json.XText);

//Output
//12.99
Get the second to last book's author:


json.XPath = "$['store']['book'][last() - 1]['author']";
Console.WriteLine(json.XText);
Console.WriteLine(json.XPath); //Note that "last() - 1" is resolved to "3".

//Output
//"Herman Melville"
//$['store']['book'][3]['author']
Display the full subtree at the current path:


json.XPath = "$.store.book[0]";
Console.WriteLine(json.XSubTree);

//Output
//            {
//                "category": "reference",
//                "author": "Nigel Rees",
//                "title": "Sayings of the Century",
//                "price": 8.95
//            }

Input Properties

The class will determine the source of the input based on which properties are set.

The order in which the input properties are checked is as follows:

When a valid source is found the search stops.

If parsing multiple documents call reset between documents to reset the parser.

Writing JSON

The JSON class can also be used to create a JSON document.

The document is written to the selected output property. In addition as the document is written, the on_json event will fire. The Text event parameter contains the part of the document currently being written.

Output Properties

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

Example

Writing a simple JSON document describing a pet:

      Json json = new Json();
      json.OutputFile = "C:\\temp\\fido.json";
      json.StartObject();
      json.PutProperty("name", "fido", 2);
      json.PutName("previousOwners");
      json.StartArray();
      json.PutValue("Steve Widgetson", 2);
      json.PutValue("Wanda Widgetson", 2);
      json.PutValue("Randy Cooper", 2);
      json.PutValue("Linda Glover", 2);
      json.EndArray();
      json.PutProperty("weightUnit", "lbs", 2);
      json.PutProperty("weight", "62", 3);
      json.EndObject();
      json.Flush();

This example results in the following JSON:

{
  "name": "fido",
  "previousOwners": [
    "Steve Widgetson",
    "Wanda Widgetson",
    "Randy Cooper",
    "Linda Glover"
  ],
  "weightUnit": "lbs",
  "weight": 62
}

When writing multiple documents call reset between documents to reset the writer.

Modifying JSON

The JSON class also allows for modifying existing JSON documents. After loading a JSON document with parse the document may be editted. The class supports inserting new values, renaming or overwriting existing values, and removing values. After editting is complete call save to output the updated JSON document.

The following methods are applicable when modifying a JSON document:

When save is called the modified JSON is written to the specified output location.

Output Properties

The class will determine the destination of the output based on which properties are set.

The order in which the output properties are checked is as follows:

Inserting New Values

To insert new values in a JSON document first load the existing document with parse. Next set x_path to the sibling or parent of the data to be inserted. Call insert_property or insert_value and pass the ValueType and Position parameters to indicate the type of data being inserted and the position.

The ValueType parameter of the above methods specifies the type of the value. Possible values are:

  • 0 (Object)
  • 1 (Array)
  • 2 (String)
  • 3 (Number)
  • 4 (Bool)
  • 5 (Null)
  • 6 (Raw)

The Position parameter of the above methods specifies the position of Value. Possible values are:

  • 0 (Before the current element)
  • 1 (After the current element)
  • 2 (The first child of the current element)
  • 3 (The last child of the current element)

For example:

Given the following JSON:

{
    "store": {
        "books": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
            }
        ]    
    }
}

Insert a new property "price" for each book:


json.XPath = "/json/store/books/[1]";
json.InsertProperty("price", "8.95", 3, 3);  //3 - Number, 3 - Last Child

json.XPath = "/json/store/books/[2]";
json.InsertProperty("price", "12.99", 3, 3); //3 - Number, 3 - Last Child

json.Save();

Produces the JSON:


{
  "store": {
    "books": [
    {
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    }
    ]
  }
}

To add a new book to the array:


json.XPath = "/json/store/books";
json.InsertValue("", 0, 3); //0 - Object, 3 - Last Child
json.XPath = "/json/store/books/[3]";
json.InsertProperty("category", "fiction", 2, 3);        //2 - String, 3 - Last Child
json.InsertProperty("author", "Herman Melville", 2, 3);  //2 - String, 3 - Last Child
json.InsertProperty("title", "Moby Dick", 2, 3);         //2 - String, 3 - Last Child
json.InsertProperty("price", "8.99", 3, 3);              //3 - Number, 3 - Last Child

json.Save();

Produces the JSON:


{
  "store": {
    "books": [
    {
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}

To add a new array property to each book:


json.XPath = "/json/store/books/[1]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[1]/tags"; 
json.InsertValue("quotes", 2, 3);      //2 - String, 3 - Last Child
json.InsertValue("british", 2, 3);     //2 - String, 3 - Last Child

json.XPath = "/json/store/books/[2]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[2]/tags";
json.InsertValue("trilogy", 2, 3);     //2 - String, 3 - Last Child
json.InsertValue("war", 2, 3);         //2 - String, 3 - Last Child

json.XPath = "/json/store/books/[3]";
json.InsertProperty("tags", "", 1, 2); //1 - Array, 2 - First Child
json.XPath = "/json/store/books/[3]/tags";
json.InsertValue("classic", 2, 3);     //2 - String, 3 - Last Child
json.InsertValue("whales", 2, 3);      //2 - String, 3 - Last Child

json.Save();

Producse the JSON:


{
  "store": {
    "books": [
    {
      "tags": ["quotes", "british"],
      "category": "reference",
      "author": "Nigel Rees",
      "title": "Sayings of the Century",
      "price": 8.95
    },
    {
      "tags": ["trilogy", "war"],
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}

Removing Values

To remove existing values set x_path and call the remove method. Continuing with the example above, to remove the first book:

json.XPath = "/json/store/books/[1]";
json.Remove();

json.Save();

Produces the JSON:


{
  "store": {
    "books": [
    {
      "tags": ["trilogy", "war"],
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "category": "fiction",
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}

To remove the "category" properties from each book:

json.XPath = "/json/store/books/[1]/category";
json.Remove();

json.XPath = "/json/store/books/[2]/category";
json.Remove();

json.Save();
Produces the JSON:


{
  "store": {
    "books": [
    {
      "tags": ["trilogy", "war"],
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "tags": ["classic", "whales"],
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 8.99
    }
    ]
  }
}

Updating Existing Names and Values

The set_name and set_value methods may be used to modify existing names and values. Continuing with the JSON directly above, to rename "tags" to "meta" and update values within the array and prices:


//Rename "tags" to "meta" for 1st book
json.XPath = "/json/store/books/[1]/tags";
json.SetName("meta");

//Update Price
json.XPath = "/json/store/books/[1]/price";
json.SetValue("13.99", 3); //3 - Number

//Rename "tags" to "meta" for 2nd book
json.XPath = "/json/store/books/[2]/tags";
json.SetName("meta");

//Update tag "whales" to "revenge"
json.XPath = "/json/store/books/[2]/meta/[2]";
json.SetValue("revenge", 2); //2 - String

//Update Price
json.XPath = "/json/store/books/[2]/price";
json.SetValue("9.99", 3); //3 - Number

json.Save();

Produces the JSON:


{
  "store": {
    "books": [
    {
      "meta": ["trilogy", "war"],
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 13.99
    },
    {
      "meta": ["classic", "revenge"],
      "author": "Herman Melville",
      "title": "Moby Dick",
      "price": 9.99
    }
    ]
  }
}

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

build_domWhen True, an internal object model of the JSON document is created.
input_dataThe JSON data to parse.
input_fileThe file to process.
output_dataThe output JSON after processing.
output_fileThe path to a local file where the output will be written.
overwriteIndicates whether or not the class should overwrite files.
validateWhen True, the parser checks that the document consists of well-formed XML.
x_child_countThe number of records in the XChild arrays.
x_child_nameThe Name property provides the name of the element.
x_child_x_textThis property contains the text of the element.
x_elementThe name of the current element.
x_element_typeIndicates the data type of the current element.
x_error_pathAn XPath to check the server response for errors.
x_parentThe parent of the current element.
x_pathProvides a way to point to a specific element in the response.
x_sub_treeA snapshot of the current element in the document.
x_textThe text of the current element.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

configSets or retrieves a configuration setting.
end_arrayWrites the closing bracket of a JSON array.
end_objectWrites the closing brace of a JSON object.
flushFlushes the parser's or writer's buffers.
has_x_pathDetermines whether a specific element exists in the document.
insert_propertyThis method inserts the specified name and value at the selected position.
insert_valueThis method inserts the specified value at the selected position.
load_schemaLoad the JSON schema.
parseThis method parses the specified JSON data.
put_nameWrites the name of a property.
put_propertyWrite a property and value.
put_rawWrites a raw JSON fragment.
put_valueWrites a value of a property.
removeRemoves the element or value set in XPath.
resetResets the class.
saveSaves the modified JSON document.
set_nameSets a new name for the element specified by XPath.
set_valueSets a new value for the element specified by XPath.
start_arrayWrites the opening bracket of a JSON array.
start_objectWrites the opening brace of a JSON object.
try_x_pathNavigates to the specified XPath if it exists.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_charactersFired for plain text segments of the input stream.
on_end_documentFires when the end of a JSON document is encountered.
on_end_elementFired when an end-element tag is encountered.
on_errorInformation about errors during data delivery.
on_ignorable_whitespaceFired when a section of ignorable whitespace is encountered.
on_jsonFires with the JSON data being written.
on_start_documentFires when the start of a new JSON document is encountered.
on_start_elementFired when a new element is encountered in the document.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

CacheContentIf true, the original JSON is stored internally in a buffer.
CloseInputStreamAfterProcessDetermines whether or not the input stream is closed after processing.
CloseOutputStreamAfterProcessDetermines whether or not the output stream is closed after processing.
ElementXPathThe XPath value for the current element in the document.
EscapeForwardSlashesWhether to escape forward slashes when writing a JSON object.
InputFormatSpecifies the input format used in JSON streaming.
PrettyPrintDetermines whether output is on one line or "pretty printed".
RecordEndDelimiterThe character sequence after the end of a JSON document.
RecordStartDelimiterThe character sequence before the start of a JSON document.
StringProcessingOptionsDefines options to use when processing string values.
XPathNotationSpecifies the expected format when setting XPath.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks 2020 Python Edition - Version 20.0 [Build 8307]