Struct ipworksmq::JSON
Properties Methods Events Config Settings Errors
The JSON struct can be used to parse and write JSON documents.
Syntax
ipworksmq::JSON
Remarks
The JSON struct offers a fast and simple way to parse and write information in JSON documents.
Parsing JSON
The JSON struct 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 xpath 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 that 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, it may be navigated by setting xpath if build_dom is True (default). If build_dom is False, parsed data are accessible only through the events.
The following events will fire during parsing:
If build_dom is True (default), xpath may be set after this method returns. xpath may be set to navigate to specific elements within the JSON document. This will be the path to a specified value within the document. Because 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 before parsing the document for the xpath functionality to be available.
The xpath property accepts both XPath and JSONPath formats. Please review the following notes 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 xpath 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. |
build_dom must be set to True before parsing the document for the xpath functionality to be available.
Simple JSON Document
{
"firstlevel": {
"one": "value",
"two": ["first", "second"],
"three": "value three"
}
}
Example 1. Setting XPath:
| Document root | JsonControl.XPath = "/" |
| Specific Element | JsonControl.XPath = "/json/firstlevel/one/" |
| i-th Child | JsonControl.XPath = "/json/firstlevel/two/[i]/" |
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].titleor in bracket-notation, as follows:
$['store']['book'][0]['title']
After setting xpath, the following properties are populated:
- xchildren
- xelement
- xelement_type
- xsub_tree
- xtext
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 struct 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 struct also can 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 struct 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:
- output_file
- output_data: The output data are written to this property if no other destination is specified.
Example. Writing a JSON Document:
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 struct also allows for modifying existing JSON documents. After loading a JSON document with parse the document may be edited. The struct supports inserting new values, renaming or overwriting existing values, and removing values. After editing 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 struct 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:
- output_file
- output_data: The output data are written to this property if no other destination is specified.
Example 1. Inserting New Values:
To insert new values in a JSON document, first load the existing document with parse. Next set xpath 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 these methods specifies the type of the value. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
The Position parameter of these methods specifies the position of Value. Possible values are as follows:
- 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();
Produces 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
}
]
}
}
Example 2. Removing Values:
To remove existing values, set xpath and call the remove method. Continuing with example 1, 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
}
]
}
}
Example 3. Updating Existing Names and Values:
The set_name and set_value methods may be used to modify existing names and values. Continuing with the preceding JSON in example 2, 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
}
]
}
}
Object Lifetime
The new() method returns a mutable reference to a struct instance. The object itself is kept in the global list maintained by IPWorksMQ. Due to this, the JSON struct cannot be disposed of automatically. Please, call the dispose(&mut self) method of JSON when you have finished using the instance.
Property List
The following is the full list of the properties of the struct with short descriptions. Click on the links for further details.
| build_dom | When True, an internal object model of the JSON document is created. |
| input_data | This property includes the JSON data to parse. |
| input_file | This property specifies the file to process. |
| output_data | This property includes the output JSON after processing. |
| output_file | This is the path to a local file where the output will be written. |
| overwrite | This property indicates whether or not the struct should overwrite files. |
| validate | This property controls whether documents are validated during parsing. |
| xchild_count | The number of records in the XChild arrays. |
| xchild_element_type | The ElementType property indicates the data type of the element. |
| xchild_name | The Name property provides the name of the element. |
| xchild_x_text | This property contains the text of the element. |
| xelement | This property includes the name of the current element. |
| xelement_type | This property indicates the data type of the current element. |
| xerror_path | This property includes an XPath to check the server response for errors. |
| xparent | The parent of the current element. |
| xpath | This property provides a way to point to a specific element in the response. |
| xsub_tree | This property includes a snapshot of the current element in the document. |
| xtext | This property includes the text of the current element. |
Method List
The following is the full list of the methods of the struct with short descriptions. Click on the links for further details.
| config | Sets or retrieves a configuration setting. |
| end_array | This method writes the closing bracket of a JSON array. |
| end_object | This method writes the closing brace of a JSON object. |
| flush | This method flushes the parser's or writer's buffers. |
| has_xpath | This method determines whether a specific element exists in the document. |
| insert_property | This method inserts the specified name and value at the selected position. |
| insert_value | This method inserts the specified value at the selected position. |
| parse | This method parses the specified JSON data. |
| put_name | This method writes the name of a property. |
| put_property | This method writes a property and value. |
| put_raw | This method writes a raw JSON fragment. |
| put_value | This method writes a value of a property. |
| remove | This method removes the element or value set in XPath. |
| reset | This method resets the struct. |
| save | This method saves the modified JSON document. |
| set_name | This method sets a new name for the element specified by XPath. |
| set_value | This method sets a new value for the element specified by XPath. |
| start_array | This method writes the opening bracket of a JSON array. |
| start_object | This event writes the opening brace of a JSON object. |
| try_xpath | This method navigates to the specified XPath if it exists. |
Event List
The following is the full list of the events fired by the struct with short descriptions. Click on the links for further details.
| on_characters | This event is fired for plaintext segments of the input stream. |
| on_end_document | This event fires when the end of a JSON document is encountered. |
| on_end_element | This event is fired when an end-element tag is encountered. |
| on_error | Fired when information is available about errors during data delivery. |
| on_ignorable_whitespace | This event is fired when a section of ignorable whitespace is encountered. |
| on_json | This event fires with the JSON data being written. |
| on_start_document | This event fires when the start of a new JSON document is encountered. |
| on_start_element | This event is fired when a new element is encountered in the document. |
Config Settings
The following is a list of config settings for the struct with short descriptions. Click on the links for further details.
| CacheContent | If true, the original JSON is stored internally in a buffer. |
| ElementXPath | The XPath value for the current element in the document. |
| EscapeForwardSlashes | Whether to escape forward slashes when writing a JSON object. |
| InputFormat | Specifies the input format used in JSON streaming. |
| PrettyPrint | Determines whether output is on one line or "pretty printed". |
| RecordEndDelimiter | The character sequence after the end of a JSON document. |
| RecordStartDelimiter | The character sequence before the start of a JSON document. |
| StringProcessingOptions | Defines options to use when processing string values. |
| XPathNotation | Specifies the expected format when setting XPath. |
build_dom property (JSON Struct)
When True, an internal object model of the JSON document is created.
Syntax
fn build_dom(&self ) -> Result<bool, IPWorksMQError>
fn set_build_dom(&self, value : bool) -> Option<IPWorksMQError>
Default Value
true
Remarks
Set this property to True when you need to browse the current document through xpath.
Data Type
bool
input_data property (JSON Struct)
This property includes the JSON data to parse.
Syntax
fn input_data(&self ) -> Result<String, IPWorksMQError>
fn set_input_data(&self, value : &str) -> Option<IPWorksMQError> fn set_input_data_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
This property specifies the JSON to be processed. Set this property before calling parse.
This may be set to a complete JSON document, or partial data. When setting partial data, call parse after each chunk of data is set. For instance:
//Parse the following in chunks: { "data": 1}
json.InputData = "{ \"data\""
json.Parse();
json.InputData = ": 1}"
json.Parse();
Input Properties
The struct 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:
- input_file
- input_data
Data Type
String
input_file property (JSON Struct)
This property specifies the file to process.
Syntax
fn input_file(&self ) -> Result<String, IPWorksMQError>
fn set_input_file(&self, value : &str) -> Option<IPWorksMQError> fn set_input_file_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
This property specifies the file to be processed. Set this property to the full or relative path to the file that will be processed.
After setting this property, call parse to parse the document.
Input Properties
The struct 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:
- input_file
- input_data
Data Type
String
output_data property (JSON Struct)
This property includes the output JSON after processing.
Syntax
fn output_data(&self ) -> Result<String, IPWorksMQError>
fn set_output_data(&self, value : &str) -> Option<IPWorksMQError> fn set_output_data_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
This property contains the resultant JSON after processing.
Output Properties
The struct 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:
- output_file
- output_data: The output data are written to this property if no other destination is specified.
Data Type
String
output_file property (JSON Struct)
This is the path to a local file where the output will be written.
Syntax
fn output_file(&self ) -> Result<String, IPWorksMQError>
fn set_output_file(&self, value : &str) -> Option<IPWorksMQError> fn set_output_file_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
This property specifies the file to which the output will be written. This may be set to an absolute or relative path.
Output Properties
The struct 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:
- output_file
- output_data: The output data are written to this property if no other destination is specified.
Data Type
String
overwrite property (JSON Struct)
This property indicates whether or not the struct should overwrite files.
Syntax
fn overwrite(&self ) -> Result<bool, IPWorksMQError>
fn set_overwrite(&self, value : bool) -> Option<IPWorksMQError>
Default Value
false
Remarks
This property indicates whether or not the struct will overwrite output_file. If overwrite is False, an error will be thrown whenever output_file exists before an operation. The default value is False.
Data Type
bool
validate property (JSON Struct)
This property controls whether documents are validated during parsing.
Syntax
fn validate(&self ) -> Result<bool, IPWorksMQError>
fn set_validate(&self, value : bool) -> Option<IPWorksMQError>
Default Value
true
Remarks
When true (default), the document will be validated during parsing. To disable validation set validate to false. Disabling validation may be useful in cases in which data can still be parsed even if the document is not well formed.
Data Type
bool
xchild_count property (JSON Struct)
The number of records in the XChild arrays.
Syntax
fn xchild_count(&self ) -> Result<i32, IPWorksMQError>
fn set_xchild_count(&self, value : i32) -> Option<IPWorksMQError>
Default Value
0
Remarks
This property controls the size of the following arrays:
The array indices start at 0 and end at xchild_count - 1.Data Type
i32
xchild_element_type property (JSON Struct)
The ElementType property indicates the data type of the element.
Syntax
fn xchild_element_type(&self , XChildIndex : i32) -> Result<i32, IPWorksMQError>
Possible Values
0 // Object
1 // Array
2 // String
3 // Number
4 // Bool
5 // Null
Default Value
0
Remarks
The xchild_element_type property indicates the data type of the element.
Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
The XChildIndex parameter specifies the index of the item in the array. The size of the array is controlled by the XChildCount property.
This property is read-only.
Data Type
i32
xchild_name property (JSON Struct)
The Name property provides the name of the element.
Syntax
fn xchild_name(&self , XChildIndex : i32) -> Result<String, IPWorksMQError>
Default Value
""
Remarks
The xchild_name property provides the name of the element. For elements within an array, the xchild_name property will be empty.
The XChildIndex parameter specifies the index of the item in the array. The size of the array is controlled by the XChildCount property.
This property is read-only.
Data Type
String
xchild_x_text property (JSON Struct)
This property contains the text of the element.
Syntax
fn xchild_x_text(&self , XChildIndex : i32) -> Result<String, IPWorksMQError>
Default Value
""
Remarks
This property contains the text of the element.
The XChildIndex parameter specifies the index of the item in the array. The size of the array is controlled by the XChildCount property.
This property is read-only.
Data Type
String
xelement property (JSON Struct)
This property includes the name of the current element.
Syntax
fn xelement(&self ) -> Result<String, IPWorksMQError>
fn set_xelement(&self, value : &str) -> Option<IPWorksMQError> fn set_xelement_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
This property contains the name of the current element. The current element is specified through the xpath property.
Data Type
String
xelement_type property (JSON Struct)
This property indicates the data type of the current element.
Syntax
fn xelement_type(&self ) -> Result<i32, IPWorksMQError>
Possible Values
0 // Object
1 // Array
2 // String
3 // Number
4 // Bool
5 // Null
Default Value
0
Remarks
This property specifies the data type of the current element. After setting xpath, this property is populated. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
NOTE: This property is not applicable when parsing a document and build_dom is False.
This property is read-only.
Data Type
i32
xerror_path property (JSON Struct)
This property includes an XPath to check the server response for errors.
Syntax
fn xerror_path(&self ) -> Result<String, IPWorksMQError>
fn set_xerror_path(&self, value : &str) -> Option<IPWorksMQError> fn set_xerror_path_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
This property contains an XPath to check the server response for errors. If the XPath exists, an exception will be thrown containing the value of the element at the path.
Data Type
String
xparent property (JSON Struct)
The parent of the current element.
Syntax
fn xparent(&self ) -> Result<String, IPWorksMQError>
Default Value
""
Remarks
This property contains the parent of the current element. The current element is specified via the xpath property.
This property is read-only.
Data Type
String
xpath property (JSON Struct)
This property provides a way to point to a specific element in the response.
Syntax
fn xpath(&self ) -> Result<String, IPWorksMQError>
fn set_xpath(&self, value : &str) -> Option<IPWorksMQError> fn set_xpath_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
xpath may be set to navigate to specific elements within the JSON document. This will be the path to a specified value within the document. Because 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 before parsing the document for the xpath functionality to be available.
The xpath property accepts both XPath and JSONPath formats. Please review the following notes 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 xpath 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. |
build_dom must be set to True before parsing the document for the xpath functionality to be available.
Simple JSON Document
{
"firstlevel": {
"one": "value",
"two": ["first", "second"],
"three": "value three"
}
}
Example 1. Setting XPath:
| Document root | JsonControl.XPath = "/" |
| Specific Element | JsonControl.XPath = "/json/firstlevel/one/" |
| i-th Child | JsonControl.XPath = "/json/firstlevel/two/[i]/" |
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].titleor in bracket-notation, as follows:
$['store']['book'][0]['title']
After setting xpath, the following properties are populated:
- xchildren
- xelement
- xelement_type
- xsub_tree
- xtext
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
// }
Data Type
String
xsub_tree property (JSON Struct)
This property includes a snapshot of the current element in the document.
Syntax
fn xsub_tree(&self ) -> Result<String, IPWorksMQError>
Default Value
""
Remarks
The current element is specified through this property. For this property to work, you must have the CacheContent set to True.
This property is read-only.
Data Type
String
xtext property (JSON Struct)
This property includes the text of the current element.
Syntax
fn xtext(&self ) -> Result<String, IPWorksMQError>
fn set_xtext(&self, value : &str) -> Option<IPWorksMQError> fn set_xtext_ref(&self, value : &String) -> Option<IPWorksMQError>
Default Value
""
Remarks
This property contains the text of the current element. The current element is specified through the xpath property.
Data Type
String
config method (JSON Struct)
Sets or retrieves a configuration setting.
Syntax
fn config(&self, configuration_string : &str) -> Result<String, IPWorksMQError>
Remarks
config is a generic method available in every struct. It is used to set and retrieve configuration settings for the struct.
These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the struct, access to these internal properties is provided through the config method.
To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).
To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.
end_array method (JSON Struct)
This method writes the closing bracket of a JSON array.
Syntax
fn end_array(&self) -> Result<(), IPWorksMQError>
Remarks
This method writes the closing bracket of a JSON array to the output. An array must already have been opened by calling start_array.
end_object method (JSON Struct)
This method writes the closing brace of a JSON object.
Syntax
fn end_object(&self) -> Result<(), IPWorksMQError>
Remarks
This method writes the closing brace of a JSON object. An object must have been started previously by calling start_object.
flush method (JSON Struct)
This method flushes the parser's or writer's buffers.
Syntax
fn flush(&self) -> Result<(), IPWorksMQError>
Remarks
When flush is called, the component flushes all of its buffers, firing events as necessary.
When parsing, the end state of the JSON is checked. If validate is also True, the parser verifies that all open elements were closed, returning an error if not.
When writing, the resultant JSON is available in one of the output properties.
Output Properties
The struct 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:
- output_file
- output_data: The output data are written to this property if no other destination is specified.
has_xpath method (JSON Struct)
This method determines whether a specific element exists in the document.
Syntax
fn has_xpath(&self, xpath : &str) -> Result<bool, IPWorksMQError>
Remarks
This method determines whether a particular XPath exists within the document. This may be used to check if a path exists before setting it through xpath.
This method returns true if the xpath exists, and false if not.
See xpath for details on the XPath syntax.
insert_property method (JSON Struct)
This method inserts the specified name and value at the selected position.
Syntax
fn insert_property(&self, name : &str, value : &str, value_type : i32, position : i32) -> Result<(), IPWorksMQError>
Remarks
This method inserts a property and its corresponding value relative to the element specified by xpath. Before calling this method, a valid JSON document must first be loaded by calling parse.
The name parameter specifies the name of the property.
The value parameter specifies the value of the property.
The value_type parameter specifies the type of the value. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
The position parameter specifies the position of value relative to the element specified by xpath. Possible values are as follows:
- 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)
See save for details.
insert_value method (JSON Struct)
This method inserts the specified value at the selected position.
Syntax
fn insert_value(&self, value : &str, value_type : i32, position : i32) -> Result<(), IPWorksMQError>
Remarks
This method inserts a value relative to the element specified by xpath. Before calling this method, a valid JSON document must first be loaded by calling parse.
The value parameter specifies the value of the property.
The value_type parameter specifies the type of the value. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
The position parameter specifies the position of value relative to the element specified by xpath. Possible values are as follows:
- 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)
See save for details.
parse method (JSON Struct)
This method parses the specified JSON data.
Syntax
fn parse(&self) -> Result<(), IPWorksMQError>
Remarks
This method parses the specified JSON data.
When parsing a document, events will fire to provide information about the parsed data. After parse returns the document, it may be navigated by setting xpath if build_dom is True (default). If build_dom is False, parsed data are accessible only through the events.
The following events will fire during parsing:
If build_dom is True (default), xpath may be set after this method returns. xpath may be set to navigate to specific elements within the JSON document. This will be the path to a specified value within the document. Because 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 before parsing the document for the xpath functionality to be available.
The xpath property accepts both XPath and JSONPath formats. Please review the following notes 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 xpath 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. |
build_dom must be set to True before parsing the document for the xpath functionality to be available.
Simple JSON Document
{
"firstlevel": {
"one": "value",
"two": ["first", "second"],
"three": "value three"
}
}
Example 1. Setting XPath:
| Document root | JsonControl.XPath = "/" |
| Specific Element | JsonControl.XPath = "/json/firstlevel/one/" |
| i-th Child | JsonControl.XPath = "/json/firstlevel/two/[i]/" |
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].titleor in bracket-notation, as follows:
$['store']['book'][0]['title']
After setting xpath, the following properties are populated:
- xchildren
- xelement
- xelement_type
- xsub_tree
- xtext
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 struct 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.
put_name method (JSON Struct)
This method writes the name of a property.
Syntax
fn put_name(&self, name : &str) -> Result<(), IPWorksMQError>
Remarks
This method writes the name of a property. The name parameter specifies the value to write.
put_property method (JSON Struct)
This method writes a property and value.
Syntax
fn put_property(&self, name : &str, value : &str, value_type : i32) -> Result<(), IPWorksMQError>
Remarks
This method writes a property and its corresponding value to the output.
The name parameter specifies the name of the property.
The value parameter specifies the value of the property.
The value_type parameter specifies the type of the value. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
put_raw method (JSON Struct)
This method writes a raw JSON fragment.
Syntax
fn put_raw(&self, text : &str) -> Result<(), IPWorksMQError>
Remarks
This method writes raw data to the output. This may be used to write any data of any format directly to the output.
put_value method (JSON Struct)
This method writes a value of a property.
Syntax
fn put_value(&self, value : &str, value_type : i32) -> Result<(), IPWorksMQError>
Remarks
This method writes the value of a property to the output. The value parameter specifies the value. The value_type parameter specifies the type of data. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
remove method (JSON Struct)
This method removes the element or value set in XPath.
Syntax
fn remove(&self) -> Result<(), IPWorksMQError>
Remarks
This method removes the current object at the specified xpath. This is used when editing previously loaded JSON documents.
See save for details.
reset method (JSON Struct)
This method resets the struct.
Syntax
fn reset(&self) -> Result<(), IPWorksMQError>
Remarks
This method resets the JSON parser.
save method (JSON Struct)
This method saves the modified JSON document.
Syntax
fn save(&self) -> Result<(), IPWorksMQError>
Remarks
This method saves the modified JSON data. This is used after editing a previously loaded JSON document.
After loading a JSON document with parse the document may be edited. The struct supports inserting new values, renaming or overwriting existing values, and removing values. After editing 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 struct 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:
- output_file
- output_data: The output data are written to this property if no other destination is specified.
Example 1. Inserting New Values:
To insert new values in a JSON document, first load the existing document with parse. Next set xpath 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 these methods specifies the type of the value. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
The Position parameter of these methods specifies the position of Value. Possible values are as follows:
- 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();
Produces 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
}
]
}
}
Example 2. Removing Values:
To remove existing values, set xpath and call the remove method. Continuing with example 1, 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
}
]
}
}
Example 3. Updating Existing Names and Values:
The set_name and set_value methods may be used to modify existing names and values. Continuing with the preceding JSON in example 2, 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
}
]
}
}
set_name method (JSON Struct)
This method sets a new name for the element specified by XPath.
Syntax
fn set_name(&self, name : &str) -> Result<(), IPWorksMQError>
Remarks
This method sets a new name for the element specified in xpath. This is used to modify an existing JSON document.
The name parameter specifies the new name of the element.
See save for details.
set_value method (JSON Struct)
This method sets a new value for the element specified by XPath.
Syntax
fn set_value(&self, value : &str, value_type : i32) -> Result<(), IPWorksMQError>
Remarks
This method sets a new value for the element specified in xpath. This is used to modify an existing JSON document.
value specifies the new value.
value_type specifies the type of the value. Possible values are as follows:
- 0 (Object)
- 1 (Array)
- 2 (String)
- 3 (Number)
- 4 (Bool)
- 5 (Null)
- 6 (Raw)
See save for details.
start_array method (JSON Struct)
This method writes the opening bracket of a JSON array.
Syntax
fn start_array(&self) -> Result<(), IPWorksMQError>
Remarks
This method writes the opening bracket of a JSON array to the output. To close the array, call end_array.
start_object method (JSON Struct)
This event writes the opening brace of a JSON object.
Syntax
fn start_object(&self) -> Result<(), IPWorksMQError>
Remarks
This method writes the opening brace of a JSON object to the output. To close the object, call end_object.
try_xpath method (JSON Struct)
This method navigates to the specified XPath if it exists.
Syntax
fn try_xpath(&self, xpath : &str) -> Result<bool, IPWorksMQError>
Remarks
This method will attempt to navigate to the specified xpath parameter if it exists within the document.
If the XPath exists, the xpath property will be updated and this method returns true.
If the XPath does not exist, the xpath property is not updated and this method returns false.
on_characters event (JSON Struct)
This event is fired for plaintext segments of the input stream.
Syntax
// JSONCharactersEventArgs carries the JSON Characters event's parameters.
pub struct JSONCharactersEventArgs {
fn text(&self) -> &String
}
// JSONCharactersEvent defines the signature of the JSON Characters event's handler function.
pub trait JSONCharactersEvent {
fn on_characters(&self, sender : JSON, e : &mut JSONCharactersEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_characters(&self) -> &'a dyn JSONCharactersEvent;
pub fn set_on_characters(&mut self, value : &'a dyn JSONCharactersEvent);
...
}
Remarks
The on_characters event provides the plaintext content of the JSON document (i.e., the text inside the elements). The text is provided through the text parameter.
The text includes white space as well as end-of-line characters, except for ignorable whitespace, which is fired through the on_ignorable_whitespace event.
on_end_document event (JSON Struct)
This event fires when the end of a JSON document is encountered.
Syntax
// JSONEndDocumentEventArgs carries the JSON EndDocument event's parameters.
pub struct JSONEndDocumentEventArgs {
}
// JSONEndDocumentEvent defines the signature of the JSON EndDocument event's handler function.
pub trait JSONEndDocumentEvent {
fn on_end_document(&self, sender : JSON, e : &mut JSONEndDocumentEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_end_document(&self) -> &'a dyn JSONEndDocumentEvent;
pub fn set_on_end_document(&mut self, value : &'a dyn JSONEndDocumentEvent);
...
}
Remarks
This event fires when parsing of a JSON document ends. This event may fire multiple times if InputFormat is set to a value that accepts multiple JSON documents.
on_end_element event (JSON Struct)
This event is fired when an end-element tag is encountered.
Syntax
// JSONEndElementEventArgs carries the JSON EndElement event's parameters.
pub struct JSONEndElementEventArgs {
fn element(&self) -> &String
}
// JSONEndElementEvent defines the signature of the JSON EndElement event's handler function.
pub trait JSONEndElementEvent {
fn on_end_element(&self, sender : JSON, e : &mut JSONEndElementEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_end_element(&self) -> &'a dyn JSONEndElementEvent;
pub fn set_on_end_element(&mut self, value : &'a dyn JSONEndElementEvent);
...
}
Remarks
The on_end_element event is fired when the end of an element is found in the document.
The element name is provided by the element parameter.
on_error event (JSON Struct)
Fired when information is available about errors during data delivery.
Syntax
// JSONErrorEventArgs carries the JSON Error event's parameters.
pub struct JSONErrorEventArgs {
fn error_code(&self) -> i32
fn description(&self) -> &String
}
// JSONErrorEvent defines the signature of the JSON Error event's handler function.
pub trait JSONErrorEvent {
fn on_error(&self, sender : JSON, e : &mut JSONErrorEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_error(&self) -> &'a dyn JSONErrorEvent;
pub fn set_on_error(&mut self, value : &'a dyn JSONErrorEvent);
...
}
Remarks
The on_error event is fired in case of exceptional conditions during message processing. Normally the struct fails with an error.
The error_code parameter contains an error code, and the description parameter contains a textual description of the error. For a list of valid error codes and their descriptions, please refer to the Error Codes section.
on_ignorable_whitespace event (JSON Struct)
This event is fired when a section of ignorable whitespace is encountered.
Syntax
// JSONIgnorableWhitespaceEventArgs carries the JSON IgnorableWhitespace event's parameters.
pub struct JSONIgnorableWhitespaceEventArgs {
fn text(&self) -> &String
}
// JSONIgnorableWhitespaceEvent defines the signature of the JSON IgnorableWhitespace event's handler function.
pub trait JSONIgnorableWhitespaceEvent {
fn on_ignorable_whitespace(&self, sender : JSON, e : &mut JSONIgnorableWhitespaceEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_ignorable_whitespace(&self) -> &'a dyn JSONIgnorableWhitespaceEvent;
pub fn set_on_ignorable_whitespace(&mut self, value : &'a dyn JSONIgnorableWhitespaceEvent);
...
}
Remarks
The ignorable whitespace section is provided by the text parameter.
on_json event (JSON Struct)
This event fires with the JSON data being written.
Syntax
// JSONJSONEventArgs carries the JSON JSON event's parameters.
pub struct JSONJSONEventArgs {
fn text(&self) -> &String
}
// JSONJSONEvent defines the signature of the JSON JSON event's handler function.
pub trait JSONJSONEvent {
fn on_json(&self, sender : JSON, e : &mut JSONJSONEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_json(&self) -> &'a dyn JSONJSONEvent;
pub fn set_on_json(&mut self, value : &'a dyn JSONJSONEvent);
...
}
Remarks
This event fires when output data are written.
text contains the JSON data currently being written.
on_start_document event (JSON Struct)
This event fires when the start of a new JSON document is encountered.
Syntax
// JSONStartDocumentEventArgs carries the JSON StartDocument event's parameters.
pub struct JSONStartDocumentEventArgs {
}
// JSONStartDocumentEvent defines the signature of the JSON StartDocument event's handler function.
pub trait JSONStartDocumentEvent {
fn on_start_document(&self, sender : JSON, e : &mut JSONStartDocumentEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_start_document(&self) -> &'a dyn JSONStartDocumentEvent;
pub fn set_on_start_document(&mut self, value : &'a dyn JSONStartDocumentEvent);
...
}
Remarks
This event fires when parsing of a JSON document begins. This event may fire multiple times if InputFormat is set to a value that accepts multiple JSON documents.
on_start_element event (JSON Struct)
This event is fired when a new element is encountered in the document.
Syntax
// JSONStartElementEventArgs carries the JSON StartElement event's parameters.
pub struct JSONStartElementEventArgs {
fn element(&self) -> &String
}
// JSONStartElementEvent defines the signature of the JSON StartElement event's handler function.
pub trait JSONStartElementEvent {
fn on_start_element(&self, sender : JSON, e : &mut JSONStartElementEventArgs);
}
impl <'a> JSON<'a> {
pub fn on_start_element(&self) -> &'a dyn JSONStartElementEvent;
pub fn set_on_start_element(&mut self, value : &'a dyn JSONStartElementEvent);
...
}
Remarks
The on_start_element event is fired when a new element is found in the document.
The element name is provided through the element parameter.
Config Settings (JSON Struct)
The struct accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the struct, access to these internal properties is provided through the config method.JSON Config Settings
string elementXPath = json.Config("ElementXPath");
NOTE: The build_dom property must be set to False.
| Value | Description |
| 0 (None - default) | Only a single JSON document is expected. Use this when a single JSON document is being parsed (most cases). |
| 1 (Line Delimited) | Multiple documents are separated by carriage return (CR), line feed (LF), or CRLF character sequences. |
| 2 (Record Separated) | A defined start and end delimiter separate documents. See RecordStartDelimiter and RecordEndDelimiter. |
| 3 (Concatenated) | New documents begin immediately after the previous documents end; no characters or delimiters separate the documents. |
json.Config("PrettyPrint=true"); // false
json.StartObject();
json.PutName("data");
json.StartObject();
json.PutProperty("id", "3", 3);
json.PutProperty("first_name", "Emma", 2);
json.PutProperty("last_name", "Wong", 2);
json.PutProperty("avatar", "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg", 2);
json.EndObject();
json.EndObject();
json.Flush();
Console.WriteLine(json.OutputData);
With PrettyPrint set to False (the default), the output would look like this:
{"data":{"id":3,"first_name":"Emma","last_name":"Wong","avatar":"https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/olegpogodaev\/128.jpg"}}
With PrettyPrint set to True, the output instead would look like this:
{
"data": {
"id": 3,
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/olegpogodaev\/128.jpg"
}
}
The default value is False.
| 0 (none - default) | No additional processing is performed. |
| 1 (unquote) | Strings are unquoted. |
| 2 (unescape) | Any escaped sequences are unescaped. |
| 3 (unquote and unescape) | Values are both unquoted and unescaped. |
"example" : "value\ntest"The following table shows the resulting value for the XText of the element:
| StringProcessingOption | Output |
| 0 (none) | "value\ntest" |
| 1 (unquote) | value\ntest |
| 2 (unescape) | "value test" |
| 3 (unquote and unescape) | value test |
- 0 (Auto - default)
- 1 (XPath)
- 2 (JSONPath)
Trappable Errors (JSON Struct)
JSON Errors
| 10231 | Unbalanced element tag. |
| 10232 | Invalid JSON markup. |
| 10233 | Invalid XPath. |
| 10234 | DOM tree unavailable (set BuildDOM to True and reparse). |
XML Errors
| 101 | Invalid attribute index. |
| 102 | No attributes available. |
| 103 | Invalid namespace index. |
| 104 | No namespaces available. |
| 105 | Invalid element index. |
| 106 | No elements available. |
| 107 | Attribute does not exist. |
| 201 | Unbalanced element tag. |
| 202 | Unknown element prefix (cannot find namespace). |
| 203 | Unknown attribute prefix (cannot find namespace). |
| 204 | Invalid XML markup. |
| 205 | Invalid end state for parser. |
| 206 | Document contains unbalanced elements. |
| 207 | Invalid xpath. |
| 208 | No such child. |
| 209 | Top element does not match start of path. |
| 210 | DOM tree unavailable (set build_dom to true and reparse). |
| 302 | Cannot open file. |
| 401 | Invalid XML would be generated. |
| 402 | An invalid XML name has been specified. |