# JSON Component

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

## Syntax

```text
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](#xpath-property-json-component) 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, [BuildDOM](#builddom-property-json-component) 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](#parse-method-json-component) returns the document, it may be navigated by setting [XPath](#xpath-property-json-component) if [BuildDOM](#builddom-property-json-component) is True (default). If [BuildDOM](#builddom-property-json-component) is False, parsed data are accessible only through the events.

The following events will fire during parsing:

- [StartElement](#startelement-event-json-component)
- [Characters](#characters-event-json-component)
- [EndElement](#endelement-event-json-component)
- [IgnorableWhitespace](#ignorablewhitespace-event-json-component)

If [BuildDOM](#builddom-property-json-component) is True (default), [XPath](#xpath-property-json-component) may be set after this method returns. [XPath](#xpath-property-json-component) 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.

[BuildDOM](#builddom-property-json-component) must be set to True before parsing the document for the [XPath](#xpath-property-json-component) functionality to be available.

The [XPath](#xpath-property-json-component) 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](#xpath-property-json-component) 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 [XPath](#xpath-property-json-component) is set to a valid path, the following properties are updated:

- [XElement](#xelement-property-json-component)
- [XElementType](#xelementtype-property-json-component)
- [XParent](#xparent-property-json-component)
- [XText](#xtext-property-json-component)
- [XSubTree](#xsubtree-property-json-component)
- XChildren

[BuildDOM](#builddom-property-json-component) must be set to True before parsing the document for the [XPath](#xpath-property-json-component) functionality to be available.

**Simple JSON Document**

```text
{
  "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]/" |

 NOTE: When using XPath notation, the root element is always referred to as "json". As in the previous 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

```text
$.store.book[0].title
```

 or in bracket-notation, as follows:

```text
$['store']['book'][0]['title']
```

After setting [XPath](#xpath-property-json-component), the following properties are populated:

- XChildren
- [XElement](#xelement-property-json-component)
- [XElementType](#xelementtype-property-json-component)
- [XSubTree](#xsubtree-property-json-component)
- [XText](#xtext-property-json-component)

 **Example 2. Setting JSONPath:**

Given the following JSON document:

```text
{
    "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:

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

//Output
//"Nigel Rees"
```

 Select the first book and inspect the children:

```text
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:

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

//Output
//12.99
```

 Get the second to last book's author:

```text
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:

```text
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:

- [InputFile](#inputfile-property-json-component)
- [InputData](#inputdata-property-json-component)

 When a valid source is found, the search stops.

If parsing multiple documents, call [Reset](#reset-method-json-component) 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 [JSON](#json-event-json-component) 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:

- [OutputFile](#outputfile-property-json-component)
- [OutputData](#outputdata-property-json-component): 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:

```text
      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:

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

When writing multiple documents, call [Reset](#reset-method-json-component) 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](#parse-method-json-component) 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](#save-method-json-component) to output the updated JSON document.

The following methods are applicable when modifying a JSON document:

- [InsertProperty](#insertproperty-method-json-component)
- [InsertValue](#insertvalue-method-json-component)
- [Remove](#remove-method-json-component)
- [Save](#save-method-json-component)
- [SetName](#setname-method-json-component)
- [SetValue](#setvalue-method-json-component)

When [Save](#save-method-json-component) 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:

- [OutputFile](#outputfile-property-json-component)
- [OutputData](#outputdata-property-json-component): 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](#parse-method-json-component). Next set [XPath](#xpath-property-json-component) to the sibling or parent of the data to be inserted. Call [InsertProperty](#insertproperty-method-json-component) or [InsertValue](#insertvalue-method-json-component) 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:

```text
{
    "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:

```csharp
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:

```text
{
  "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:

```csharp
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:

```text
{
  "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:

```csharp
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:

```text
{
  "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](#xpath-property-json-component) and call the [Remove](#remove-method-json-component) method. Continuing with example 1, to remove the first book:

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

json.Save();
```

Produces the JSON:

```text
{
  "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:

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

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

json.Save();
```

Produces the JSON:

```text
{
  "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 [SetName](#setname-method-json-component) and [SetValue](#setvalue-method-json-component) 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:

```csharp
//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:

```text
{
  "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 component with short descriptions. Click on the links for further details.*

|  |  |
| --- | --- |
| [BuildDOM](#builddom-property-json-component) | When True, an internal object model of the JSON document is created. |
| [InputData](#inputdata-property-json-component) | This property includes the JSON data to parse. |
| [InputFile](#inputfile-property-json-component) | This property specifies the file to process. |
| [OutputData](#outputdata-property-json-component) | This property includes the output JSON after processing. |
| [OutputFile](#outputfile-property-json-component) | This is the path to a local file where the output will be written. |
| [Overwrite](#overwrite-property-json-component) | This property indicates whether or not the class should overwrite files. |
| [Validate](#validate-property-json-component) | This property controls whether documents are validated during parsing. |
| [XChildCount](#xchildcount-property-json-component) | The number of records in the XChild arrays. |
| [XChildElementType](#xchildelementtype-property-json-component) | The ElementType property indicates the data type of the element. |
| [XChildName](#xchildname-property-json-component) | The Name property provides the name of the element. |
| [XChildXText](#xchildxtext-property-json-component) | This property contains the text of the element. |
| [XElement](#xelement-property-json-component) | This property includes the name of the current element. |
| [XElementType](#xelementtype-property-json-component) | This property indicates the data type of the current element. |
| [XErrorPath](#xerrorpath-property-json-component) | This property includes an XPath to check the server response for errors. |
| [XParent](#xparent-property-json-component) | The parent of the current element. |
| [XPath](#xpath-property-json-component) | This property provides a way to point to a specific element in the response. |
| [XSubTree](#xsubtree-property-json-component) | This property includes a snapshot of the current element in the document. |
| [XText](#xtext-property-json-component) | This property includes the text of the current element. |

## Method List

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

|  |  |
| --- | --- |
| [Config](#config-method-json-component) | Sets or retrieves a configuration setting. |
| [EndArray](#endarray-method-json-component) | This method writes the closing bracket of a JSON array. |
| [EndObject](#endobject-method-json-component) | This method writes the closing brace of a JSON object. |
| [Flush](#flush-method-json-component) | This method flushes the parser's or writer's buffers. |
| [HasXPath](#hasxpath-method-json-component) | This method determines whether a specific element exists in the document. |
| [InsertProperty](#insertproperty-method-json-component) | This method inserts the specified name and value at the selected position. |
| [InsertValue](#insertvalue-method-json-component) | This method inserts the specified value at the selected position. |
| [Parse](#parse-method-json-component) | This method parses the specified JSON data. |
| [PutName](#putname-method-json-component) | This method writes the name of a property. |
| [PutProperty](#putproperty-method-json-component) | This method writes a property and value. |
| [PutRaw](#putraw-method-json-component) | This method writes a raw JSON fragment. |
| [PutValue](#putvalue-method-json-component) | This method writes a value of a property. |
| [Remove](#remove-method-json-component) | This method removes the element or value set in XPath. |
| [Reset](#reset-method-json-component) | This method resets the class. |
| [Save](#save-method-json-component) | This method saves the modified JSON document. |
| [SetName](#setname-method-json-component) | This method sets a new name for the element specified by XPath. |
| [SetValue](#setvalue-method-json-component) | This method sets a new value for the element specified by XPath. |
| [StartArray](#startarray-method-json-component) | This method writes the opening bracket of a JSON array. |
| [StartObject](#startobject-method-json-component) | This event writes the opening brace of a JSON object. |
| [TryXPath](#tryxpath-method-json-component) | This method navigates to the specified XPath if it exists. |

## Event List

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

|  |  |
| --- | --- |
| [Characters](#characters-event-json-component) | This event is fired for plaintext segments of the input stream. |
| [EndDocument](#enddocument-event-json-component) | This event fires when the end of a JSON document is encountered. |
| [EndElement](#endelement-event-json-component) | This event is fired when an end-element tag is encountered. |
| [Error](#error-event-json-component) | Fired when information is available about errors during data delivery. |
| [IgnorableWhitespace](#ignorablewhitespace-event-json-component) | This event is fired when a section of ignorable whitespace is encountered. |
| [JSON](#json-event-json-component) | This event fires with the JSON data being written. |
| [StartDocument](#startdocument-event-json-component) | This event fires when the start of a new JSON document is encountered. |
| [StartElement](#startelement-event-json-component) | 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 component with short descriptions. Click on the links for further details.*

|  |  |
| --- | --- |
| [CacheContent](#CacheContent) | If true, the original JSON is stored internally in a buffer. |
| [ElementXPath](#ElementXPath) | The XPath value for the current element in the document. |
| [EscapeForwardSlashes](#EscapeForwardSlashes) | Whether to escape forward slashes when writing a JSON object. |
| [InputFormat](#InputFormat) | Specifies the input format used in JSON streaming. |
| [PrettyPrint](#PrettyPrint) | Determines whether output is on one line or "pretty printed". |
| [RecordEndDelimiter](#RecordEndDelimiter) | The character sequence after the end of a JSON document. |
| [RecordStartDelimiter](#RecordStartDelimiter) | The character sequence before the start of a JSON document. |
| [StringProcessingOptions](#StringProcessingOptions) | Defines options to use when processing string values. |
| [XPathNotation](#XPathNotation) | Specifies the expected format when setting XPath. |

# BuildDOM Property ([JSON](#json-component) Component)

When True, an internal object model of the JSON document is created.

## Syntax

*Go Syntax*

```text
func (obj *JSON) BuildDOM() (bool, error)func (obj *JSON) SetBuildDOM(value bool) error
```

## Default Value

true

## Remarks

Set this property to True when you need to browse the current document through [XPath](#xpath-property-json-component).

## Data Type

**bool**

# InputData Property ([JSON](#json-component) Component)

This property includes the JSON data to parse.

## Syntax

*Go Syntax*

```text
func (obj *JSON) InputData() (string, error)func (obj *JSON) SetInputData(value string) error
```

## Default Value

""

## Remarks

This property specifies the JSON to be processed. Set this property before calling [Parse](#parse-method-json-component).

This may be set to a complete JSON document, or partial data. When setting partial data, call [Parse](#parse-method-json-component) after each chunk of data is set. For instance:

```text
//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:

- [InputFile](#inputfile-property-json-component)
- InputData

 When a valid source is found, the search stops.

## Data Type

**string**

# InputFile Property ([JSON](#json-component) Component)

This property specifies the file to process.

## Syntax

*Go Syntax*

```text
func (obj *JSON) InputFile() (string, error)func (obj *JSON) SetInputFile(value string) error
```

## 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](#parse-method-json-component) 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:

- InputFile
- [InputData](#inputdata-property-json-component)

 When a valid source is found, the search stops.

## Data Type

**string**

# OutputData Property ([JSON](#json-component) Component)

This property includes the output JSON after processing.

## Syntax

*Go Syntax*

```text
func (obj *JSON) OutputData() (string, error)func (obj *JSON) SetOutputData(value string) error
```

## 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:

- [OutputFile](#outputfile-property-json-component)
- OutputData: The output data are written to this property if no other destination is specified.

## Data Type

**string**

# OutputFile Property ([JSON](#json-component) Component)

This is the path to a local file where the output will be written.

## Syntax

*Go Syntax*

```text
func (obj *JSON) OutputFile() (string, error)func (obj *JSON) SetOutputFile(value string) error
```

## 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:

- OutputFile
- [OutputData](#outputdata-property-json-component): The output data are written to this property if no other destination is specified.

## Data Type

**string**

# Overwrite Property ([JSON](#json-component) Component)

This property indicates whether or not the class should overwrite files.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Overwrite() (bool, error)func (obj *JSON) SetOverwrite(value bool) error
```

## Default Value

false

## Remarks

This property indicates whether or not the struct will overwrite [OutputFile](#outputfile-property-json-component). If Overwrite is False, an error will be thrown whenever [OutputFile](#outputfile-property-json-component) exists before an operation. The default value is False.

## Data Type

**bool**

# Validate Property ([JSON](#json-component) Component)

This property controls whether documents are validated during parsing.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Validate() (bool, error)func (obj *JSON) SetValidate(value bool) error
```

## 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**

# XChildCount Property ([JSON](#json-component) Component)

The number of records in the XChild arrays.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XChildCount() (int32, error)func (obj *JSON) SetXChildCount(value int32) error
```

## Default Value

0

## Remarks

This property controls the size of the following arrays:

- [XChildElementType](#xchildelementtype-property-json-component)
- [XChildName](#xchildname-property-json-component)
- [XChildXText](#xchildxtext-property-json-component)

The array indices start at *0* and end at *XChildCount - 1*.

## Data Type

**int32**

# XChildElementType Property ([JSON](#json-component) Component)

The ElementType property indicates the data type of the element.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XChildElementType(XChildIndex int32) (int32, error)
```

## Possible Values

```text
0   // Object1   // Array2   // String3   // Number4   // Bool5   // Null
```

## Default Value

0

## Remarks

The [XChildElementType](#xchildelementtype-property-json-component) 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](#xchildcount-property-json-component) property.

This property is read-only.

## Data Type

**int32**

# XChildName Property ([JSON](#json-component) Component)

The Name property provides the name of the element.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XChildName(XChildIndex int32) (string, error)
```

## Default Value

""

## Remarks

The [XChildName](#xchildname-property-json-component) property provides the name of the element. For elements within an array, the [XChildName](#xchildname-property-json-component) 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](#xchildcount-property-json-component) property.

This property is read-only.

## Data Type

**string**

# XChildXText Property ([JSON](#json-component) Component)

This property contains the text of the element.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XChildXText(XChildIndex int32) (string, error)
```

## 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](#xchildcount-property-json-component) property.

This property is read-only.

## Data Type

**string**

# XElement Property ([JSON](#json-component) Component)

This property includes the name of the current element.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XElement() (string, error)func (obj *JSON) SetXElement(value string) error
```

## Default Value

""

## Remarks

This property contains the name of the current element. The current element is specified through the [XPath](#xpath-property-json-component) property.

## Data Type

**string**

# XElementType Property ([JSON](#json-component) Component)

This property indicates the data type of the current element.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XElementType() (int32, error)
```

## Possible Values

```text
0   // Object1   // Array2   // String3   // Number4   // Bool5   // Null
```

## Default Value

0

## Remarks

This property specifies the data type of the current element. After setting [XPath](#xpath-property-json-component), 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 [BuildDOM](#builddom-property-json-component) is False.

This property is read-only.

## Data Type

**int32**

# XErrorPath Property ([JSON](#json-component) Component)

This property includes an XPath to check the server response for errors.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XErrorPath() (string, error)func (obj *JSON) SetXErrorPath(value string) error
```

## 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](#json-component) Component)

The parent of the current element.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XParent() (string, error)
```

## Default Value

""

## Remarks

This property contains the parent of the current element. The current element is specified via the [XPath](#xpath-property-json-component) property.

This property is read-only.

## Data Type

**string**

# XPath Property ([JSON](#json-component) Component)

This property provides a way to point to a specific element in the response.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XPath() (string, error)func (obj *JSON) SetXPath(value string) error
```

## 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.

[BuildDOM](#builddom-property-json-component) 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. |

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

- [XElement](#xelement-property-json-component)
- [XElementType](#xelementtype-property-json-component)
- [XParent](#xparent-property-json-component)
- [XText](#xtext-property-json-component)
- [XSubTree](#xsubtree-property-json-component)
- XChildren

[BuildDOM](#builddom-property-json-component) must be set to True before parsing the document for the XPath functionality to be available.

**Simple JSON Document**

```text
{
  "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]/" |

 NOTE: When using XPath notation, the root element is always referred to as "json". As in the previous 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

```text
$.store.book[0].title
```

 or in bracket-notation, as follows:

```text
$['store']['book'][0]['title']
```

After setting XPath, the following properties are populated:

- XChildren
- [XElement](#xelement-property-json-component)
- [XElementType](#xelementtype-property-json-component)
- [XSubTree](#xsubtree-property-json-component)
- [XText](#xtext-property-json-component)

 **Example 2. Setting JSONPath:**

Given the following JSON document:

```text
{
    "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:

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

//Output
//"Nigel Rees"
```

 Select the first book and inspect the children:

```text
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:

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

//Output
//12.99
```

 Get the second to last book's author:

```text
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:

```text
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**

# XSubTree Property ([JSON](#json-component) Component)

This property includes a snapshot of the current element in the document.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XSubTree() (string, error)
```

## Default Value

""

## Remarks

The current element is specified through this property. For this property to work, you must have the [CacheContent](#CacheContent) set to True.

This property is read-only.

## Data Type

**string**

# XText Property ([JSON](#json-component) Component)

This property includes the text of the current element.

## Syntax

*Go Syntax*

```text
func (obj *JSON) XText() (string, error)func (obj *JSON) SetXText(value string) error
```

## Default Value

""

## Remarks

This property contains the text of the current element. The current element is specified through the [XPath](#xpath-property-json-component) property.

## Data Type

**string**

# Config Method ([JSON](#json-component) Component)

Sets or retrieves a configuration setting.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Config(ConfigurationString string) (string, error)
```

## Remarks

Config is a generic method available in every struct. It is used to set and retrieve [configuration settings](#config-settings-json-component) 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](#config-settings-json-component), you must call *Config("PROPERTY")*. The value will be returned as a string.

# EndArray Method ([JSON](#json-component) Component)

This method writes the closing bracket of a JSON array.

## Syntax

*Go Syntax*

```text
func (obj *JSON) EndArray() error
```

## Remarks

This method writes the closing bracket of a JSON array to the output. An array must already have been opened by calling [StartArray](#startarray-method-json-component).

# EndObject Method ([JSON](#json-component) Component)

This method writes the closing brace of a JSON object.

## Syntax

*Go Syntax*

```text
func (obj *JSON) EndObject() error
```

## Remarks

This method writes the closing brace of a JSON object. An object must have been started previously by calling [StartObject](#startobject-method-json-component).

# Flush Method ([JSON](#json-component) Component)

This method flushes the parser's or writer's buffers.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Flush() error
```

## 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](#validate-property-json-component) 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:

- [OutputFile](#outputfile-property-json-component)
- [OutputData](#outputdata-property-json-component): The output data are written to this property if no other destination is specified.

# HasXPath Method ([JSON](#json-component) Component)

This method determines whether a specific element exists in the document.

## Syntax

*Go Syntax*

```text
func (obj *JSON) HasXPath(XPath string) (bool, error)
```

## 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](#xpath-property-json-component).

This method returns *true* if the *XPath* exists, and *false* if not.

See [XPath](#xpath-property-json-component) for details on the XPath syntax.

# InsertProperty Method ([JSON](#json-component) Component)

This method inserts the specified name and value at the selected position.

## Syntax

*Go Syntax*

```text
func (obj *JSON) InsertProperty(Name string, Value string, ValueType int32, Position int32) error
```

## Remarks

This method inserts a property and its corresponding value relative to the element specified by [XPath](#xpath-property-json-component). Before calling this method, a valid JSON document must first be loaded by calling [Parse](#parse-method-json-component).

The *Name* parameter specifies the name of the property.

The *Value* parameter specifies the value of the property.

The *ValueType* 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](#xpath-property-json-component). 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](#save-method-json-component) for details.

# InsertValue Method ([JSON](#json-component) Component)

This method inserts the specified value at the selected position.

## Syntax

*Go Syntax*

```text
func (obj *JSON) InsertValue(Value string, ValueType int32, Position int32) error
```

## Remarks

This method inserts a value relative to the element specified by [XPath](#xpath-property-json-component). Before calling this method, a valid JSON document must first be loaded by calling [Parse](#parse-method-json-component).

The *Value* parameter specifies the value of the property.

The *ValueType* 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](#xpath-property-json-component). 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](#save-method-json-component) for details.

# Parse Method ([JSON](#json-component) Component)

This method parses the specified JSON data.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Parse() error
```

## 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](#xpath-property-json-component) if [BuildDOM](#builddom-property-json-component) is True (default). If [BuildDOM](#builddom-property-json-component) is False, parsed data are accessible only through the events.

The following events will fire during parsing:

- [StartElement](#startelement-event-json-component)
- [Characters](#characters-event-json-component)
- [EndElement](#endelement-event-json-component)
- [IgnorableWhitespace](#ignorablewhitespace-event-json-component)

If [BuildDOM](#builddom-property-json-component) is True (default), [XPath](#xpath-property-json-component) may be set after this method returns. [XPath](#xpath-property-json-component) 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.

[BuildDOM](#builddom-property-json-component) must be set to True before parsing the document for the [XPath](#xpath-property-json-component) functionality to be available.

The [XPath](#xpath-property-json-component) 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](#xpath-property-json-component) 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 [XPath](#xpath-property-json-component) is set to a valid path, the following properties are updated:

- [XElement](#xelement-property-json-component)
- [XElementType](#xelementtype-property-json-component)
- [XParent](#xparent-property-json-component)
- [XText](#xtext-property-json-component)
- [XSubTree](#xsubtree-property-json-component)
- XChildren

[BuildDOM](#builddom-property-json-component) must be set to True before parsing the document for the [XPath](#xpath-property-json-component) functionality to be available.

**Simple JSON Document**

```text
{
  "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]/" |

 NOTE: When using XPath notation, the root element is always referred to as "json". As in the previous 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

```text
$.store.book[0].title
```

 or in bracket-notation, as follows:

```text
$['store']['book'][0]['title']
```

After setting [XPath](#xpath-property-json-component), the following properties are populated:

- XChildren
- [XElement](#xelement-property-json-component)
- [XElementType](#xelementtype-property-json-component)
- [XSubTree](#xsubtree-property-json-component)
- [XText](#xtext-property-json-component)

 **Example 2. Setting JSONPath:**

Given the following JSON document:

```text
{
    "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:

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

//Output
//"Nigel Rees"
```

 Select the first book and inspect the children:

```text
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:

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

//Output
//12.99
```

 Get the second to last book's author:

```text
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:

```text
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:

- [InputFile](#inputfile-property-json-component)
- [InputData](#inputdata-property-json-component)

 When a valid source is found, the search stops.

If parsing multiple documents, call [Reset](#reset-method-json-component) between documents to reset the parser.

# PutName Method ([JSON](#json-component) Component)

This method writes the name of a property.

## Syntax

*Go Syntax*

```text
func (obj *JSON) PutName(Name string) error
```

## Remarks

This method writes the name of a property. The *Name* parameter specifies the value to write.

# PutProperty Method ([JSON](#json-component) Component)

This method writes a property and value.

## Syntax

*Go Syntax*

```text
func (obj *JSON) PutProperty(Name string, Value string, ValueType int32) error
```

## 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 *ValueType* 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)

# PutRaw Method ([JSON](#json-component) Component)

This method writes a raw JSON fragment.

## Syntax

*Go Syntax*

```text
func (obj *JSON) PutRaw(Text string) error
```

## Remarks

This method writes raw data to the output. This may be used to write any data of any format directly to the output.

# PutValue Method ([JSON](#json-component) Component)

This method writes a value of a property.

## Syntax

*Go Syntax*

```text
func (obj *JSON) PutValue(Value string, ValueType int32) error
```

## Remarks

This method writes the value of a property to the output. The *Value* parameter specifies the value. The *ValueType* 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](#json-component) Component)

This method removes the element or value set in XPath.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Remove() error
```

## Remarks

This method removes the current object at the specified [XPath](#xpath-property-json-component). This is used when editing previously loaded JSON documents.

See [Save](#save-method-json-component) for details.

# Reset Method ([JSON](#json-component) Component)

This method resets the class.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Reset() error
```

## Remarks

This method resets the JSON parser.

# Save Method ([JSON](#json-component) Component)

This method saves the modified JSON document.

## Syntax

*Go Syntax*

```text
func (obj *JSON) Save() error
```

## 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](#parse-method-json-component) 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:

- [InsertProperty](#insertproperty-method-json-component)
- [InsertValue](#insertvalue-method-json-component)
- [Remove](#remove-method-json-component)
- Save
- [SetName](#setname-method-json-component)
- [SetValue](#setvalue-method-json-component)

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:

- [OutputFile](#outputfile-property-json-component)
- [OutputData](#outputdata-property-json-component): 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](#parse-method-json-component). Next set [XPath](#xpath-property-json-component) to the sibling or parent of the data to be inserted. Call [InsertProperty](#insertproperty-method-json-component) or [InsertValue](#insertvalue-method-json-component) 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:

```text
{
    "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:

```csharp
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:

```text
{
  "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:

```csharp
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:

```text
{
  "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:

```csharp
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:

```text
{
  "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](#xpath-property-json-component) and call the [Remove](#remove-method-json-component) method. Continuing with example 1, to remove the first book:

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

json.Save();
```

Produces the JSON:

```text
{
  "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:

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

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

json.Save();
```

Produces the JSON:

```text
{
  "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 [SetName](#setname-method-json-component) and [SetValue](#setvalue-method-json-component) 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:

```csharp
//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:

```text
{
  "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
    }
    ]
  }
}
```

# SetName Method ([JSON](#json-component) Component)

This method sets a new name for the element specified by XPath.

## Syntax

*Go Syntax*

```text
func (obj *JSON) SetName(Name string) error
```

## Remarks

This method sets a new name for the element specified in [XPath](#xpath-property-json-component). This is used to modify an existing JSON document.

The *Name* parameter specifies the new name of the element.

See [Save](#save-method-json-component) for details.

# SetValue Method ([JSON](#json-component) Component)

This method sets a new value for the element specified by XPath.

## Syntax

*Go Syntax*

```text
func (obj *JSON) SetValue(Value string, ValueType int32) error
```

## Remarks

This method sets a new value for the element specified in [XPath](#xpath-property-json-component). This is used to modify an existing JSON document.

*Value* specifies the new value.

*ValueType* 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](#save-method-json-component) for details.

# StartArray Method ([JSON](#json-component) Component)

This method writes the opening bracket of a JSON array.

## Syntax

*Go Syntax*

```text
func (obj *JSON) StartArray() error
```

## Remarks

This method writes the opening bracket of a JSON array to the output. To close the array, call [EndArray](#endarray-method-json-component).

# StartObject Method ([JSON](#json-component) Component)

This event writes the opening brace of a JSON object.

## Syntax

*Go Syntax*

```text
func (obj *JSON) StartObject() error
```

## Remarks

This method writes the opening brace of a JSON object to the output. To close the object, call [EndObject](#endobject-method-json-component).

# TryXPath Method ([JSON](#json-component) Component)

This method navigates to the specified XPath if it exists.

## Syntax

*Go Syntax*

```text
func (obj *JSON) TryXPath(xpath string) (bool, error)
```

## Remarks

This method will attempt to navigate to the specified *XPath* parameter if it exists within the document.

If the XPath exists, the [XPath](#xpath-property-json-component) property will be updated and this method returns *true*.

If the XPath does not exist, the [XPath](#xpath-property-json-component) property is not updated and this method returns *false*.

# Characters Event ([JSON](#json-component) Component)

This event is fired for plaintext segments of the input stream.

## Syntax

*Go Syntax*

```text
// JSONCharactersEventArgs carries the JSON Characters event's parameters.
type JSONCharactersEventArgs struct {...}

func (args *JSONCharactersEventArgs) Text() string
// JSONCharactersEvent defines the signature of the JSON Characters event's handler function.
type JSONCharactersEvent func(sender *JSON, args *JSONCharactersEventArgs)

func (obj *JSON) GetOnCharactersHandler() JSONCharactersEvent
func (obj *JSON) SetOnCharactersHandler(handlerFunc JSONCharactersEvent)
```

## Remarks

The 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 [IgnorableWhitespace](#ignorablewhitespace-event-json-component) event.

# EndDocument Event ([JSON](#json-component) Component)

This event fires when the end of a JSON document is encountered.

## Syntax

*Go Syntax*

```text
// JSONEndDocumentEventArgs carries the JSON EndDocument event's parameters.
type JSONEndDocumentEventArgs struct {...}

// JSONEndDocumentEvent defines the signature of the JSON EndDocument event's handler function.
type JSONEndDocumentEvent func(sender *JSON, args *JSONEndDocumentEventArgs)

func (obj *JSON) GetOnEndDocumentHandler() JSONEndDocumentEvent
func (obj *JSON) SetOnEndDocumentHandler(handlerFunc JSONEndDocumentEvent)
```

## Remarks

This event fires when parsing of a JSON document ends. This event may fire multiple times if [InputFormat](#InputFormat) is set to a value that accepts multiple JSON documents.

# EndElement Event ([JSON](#json-component) Component)

This event is fired when an end-element tag is encountered.

## Syntax

*Go Syntax*

```text
// JSONEndElementEventArgs carries the JSON EndElement event's parameters.
type JSONEndElementEventArgs struct {...}

func (args *JSONEndElementEventArgs) Element() string
// JSONEndElementEvent defines the signature of the JSON EndElement event's handler function.
type JSONEndElementEvent func(sender *JSON, args *JSONEndElementEventArgs)

func (obj *JSON) GetOnEndElementHandler() JSONEndElementEvent
func (obj *JSON) SetOnEndElementHandler(handlerFunc JSONEndElementEvent)
```

## Remarks

The EndElement event is fired when the end of an element is found in the document.

The element name is provided by the *Element* parameter.

# Error Event ([JSON](#json-component) Component)

Fired when information is available about errors during data delivery.

## Syntax

*Go Syntax*

```text
// JSONErrorEventArgs carries the JSON Error event's parameters.
type JSONErrorEventArgs struct {...}

func (args *JSONErrorEventArgs) ErrorCode() int32
func (args *JSONErrorEventArgs) Description() string
// JSONErrorEvent defines the signature of the JSON Error event's handler function.
type JSONErrorEvent func(sender *JSON, args *JSONErrorEventArgs)

func (obj *JSON) GetOnErrorHandler() JSONErrorEvent
func (obj *JSON) SetOnErrorHandler(handlerFunc JSONErrorEvent)
```

## Remarks

The Error event is fired in case of exceptional conditions during message processing. Normally the struct fails with an error.

The *ErrorCode* 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](#trappable-errors-json-component) section.

# IgnorableWhitespace Event ([JSON](#json-component) Component)

This event is fired when a section of ignorable whitespace is encountered.

## Syntax

*Go Syntax*

```text
// JSONIgnorableWhitespaceEventArgs carries the JSON IgnorableWhitespace event's parameters.
type JSONIgnorableWhitespaceEventArgs struct {...}

func (args *JSONIgnorableWhitespaceEventArgs) Text() string
// JSONIgnorableWhitespaceEvent defines the signature of the JSON IgnorableWhitespace event's handler function.
type JSONIgnorableWhitespaceEvent func(sender *JSON, args *JSONIgnorableWhitespaceEventArgs)

func (obj *JSON) GetOnIgnorableWhitespaceHandler() JSONIgnorableWhitespaceEvent
func (obj *JSON) SetOnIgnorableWhitespaceHandler(handlerFunc JSONIgnorableWhitespaceEvent)
```

## Remarks

The ignorable whitespace section is provided by the *Text* parameter.

# JSON Event ([JSON](#json-component) Component)

This event fires with the JSON data being written.

## Syntax

*Go Syntax*

```text
// JSONJSONEventArgs carries the JSON JSON event's parameters.
type JSONJSONEventArgs struct {...}

func (args *JSONJSONEventArgs) Text() string
// JSONJSONEvent defines the signature of the JSON JSON event's handler function.
type JSONJSONEvent func(sender *JSON, args *JSONJSONEventArgs)

func (obj *JSON) GetOnJSONHandler() JSONJSONEvent
func (obj *JSON) SetOnJSONHandler(handlerFunc JSONJSONEvent)
```

## Remarks

This event fires when output data are written.

*Text* contains the JSON data currently being written.

# StartDocument Event ([JSON](#json-component) Component)

This event fires when the start of a new JSON document is encountered.

## Syntax

*Go Syntax*

```text
// JSONStartDocumentEventArgs carries the JSON StartDocument event's parameters.
type JSONStartDocumentEventArgs struct {...}

// JSONStartDocumentEvent defines the signature of the JSON StartDocument event's handler function.
type JSONStartDocumentEvent func(sender *JSON, args *JSONStartDocumentEventArgs)

func (obj *JSON) GetOnStartDocumentHandler() JSONStartDocumentEvent
func (obj *JSON) SetOnStartDocumentHandler(handlerFunc JSONStartDocumentEvent)
```

## Remarks

This event fires when parsing of a JSON document begins. This event may fire multiple times if [InputFormat](#InputFormat) is set to a value that accepts multiple JSON documents.

# StartElement Event ([JSON](#json-component) Component)

This event is fired when a new element is encountered in the document.

## Syntax

*Go Syntax*

```text
// JSONStartElementEventArgs carries the JSON StartElement event's parameters.
type JSONStartElementEventArgs struct {...}

func (args *JSONStartElementEventArgs) Element() string
// JSONStartElementEvent defines the signature of the JSON StartElement event's handler function.
type JSONStartElementEvent func(sender *JSON, args *JSONStartElementEventArgs)

func (obj *JSON) GetOnStartElementHandler() JSONStartElementEvent
func (obj *JSON) SetOnStartElementHandler(handlerFunc JSONStartElementEvent)
```

## Remarks

The StartElement event is fired when a new element is found in the document.

The element name is provided through the *Element* parameter.

# Config Settings ([JSON](#json-component) Component)

 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](#config-method-json-component) method.

### JSON Config Settings

**CacheContent**: If true, the original JSON is stored internally in a buffer.This configuration setting controls whether the struct retains the entire original JSON data in memory (default: *true*). The cached data is used by the [XSubTree](#xsubtree-property-json-component) property to return position-based subtrees from the original JSON. When CacheContents is disabled, this cached data is cleared to reduce memory usage when processing large JSON files, and XSubTree always returns an empty string as a result. Other X* properties rely on the internal [BuildDOM](#builddom-property-json-component) representation and are not affected by this setting.

**ElementXPath**: The XPath value for the current element in the document.This configuration setting holds the current XPath value when the document is parsed. When queried from inside the [StartElement](#startelement-event-json-component) event, the corresponding element's XPath value will be returned. For instance:

```csharp
string elementXPath = json.Config("ElementXPath");
```

NOTE: The [BuildDOM](#builddom-property-json-component) property must be set to *False*.

**EscapeForwardSlashes**: Whether to escape forward slashes when writing a JSON object.This configuration setting specifies whether forward slashes (*/*) are escaped when creating a JSON object using the struct. This does not affect parsing of JSON. It is applicable only when JSON values are written.

**InputFormat**: Specifies the input format used in JSON streaming.This configuration setting specifies how JSON documents are formatted as they are input to the struct. This setting is designed for use when data are provided via JSON streaming. This means multiple documents may be parsed by the struct. This setting is applicable only when [BuildDOM](#builddom-property-json-component) is set to False. Possible values are as follows:

| 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](#RecordStartDelimiter) and [RecordEndDelimiter](#RecordEndDelimiter). |
| 3 (Concatenated) | New documents begin immediately after the previous documents end; no characters or delimiters separate the documents. |

**PrettyPrint**: Determines whether output is on one line or "pretty printed".The value of this configuration setting determines whether output is generated as a single line of JSON or as multiple "pretty printed" lines. The following example code, provides a better understanding of this configuration setting:

```csharp
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:

```text
{"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:

```text
{
  "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.

**RecordEndDelimiter**: The character sequence after the end of a JSON document.This configuration setting is used in conjunction with [InputFormat](#InputFormat) to specify the character sequence that is expected after the end of a JSON document.

**RecordStartDelimiter**: The character sequence before the start of a JSON document.This configuration setting is used in conjunction with [InputFormat](#InputFormat) to specify the character sequence that is expected before the start of a JSON document.

**StringProcessingOptions**: Defines options to use when processing string values.This configuration setting determines what additional processing is performed on string values during parsing. By default, no additional processing is performed and the string is returned as is from the document. Strings also may be unquoted, unescaped, or both. Possible values follow:

|  |  |
| --- | --- |
| 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. |

 For instance, given the JSON element:

```text
"example" : "value\ntest"
```

 The following table shows the resulting value for the XText of the element:

```text
"value\ntest"
```

```text
value\ntest
```

```text
"value
test"
```

```text
value
test
```

| StringProcessingOption | Output |
| --- | --- |
| 0 (none) |  |
| 1 (unquote) |  |
| 2 (unescape) |  |
| 3 (unquote and unescape) |  |

**XPathNotation**: Specifies the expected format when setting XPath.This configuration setting optionally specifies the expected input format when setting [XPath](#xpath-property-json-component). Possible values follow:

- 0 (Auto - default)
- 1 (XPath)
- 2 (JSONPath)

 In most cases, the default of 0 (Auto) is sufficient. The struct will determine whether the path value is in XPath or JSONPath format automatically. If desired, the type may be explicitly set to either XPath or JSONPath using the values above.

# Trappable Errors ([JSON](#json-component) Component)

### 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](#xpath-property-json-component). |
| 208 | No such child. |
| 209 | Top element does not match start of path. |
| 210 | DOM tree unavailable (set [BuildDOM](#builddom-property-json-component) to true and reparse). |
| 302 | Cannot open file. |
| 401 | Invalid XML would be generated. |
| 402 | An invalid XML name has been specified. |
