JSON support for Free Pascal

The JSON unit implements JSON support for Free Pascal. It contains the data structures ( and descendent objects) to treat JSON data and output JSON as a string . The generated JSON can be formatted in several ways .

Using the JSON data structures is simple. Instantiate an appropriate descendent of TJSONData, set the data and call AsJSON. The following JSON data types are supported:

Numbers
in one of , or , depending on the type of the number.
Strings
in .
Boolean
in .
null
is supported using
Array
is supported using
Object
is supported using

The constructors of these objects allow to set the value, making them very easy to use. The memory management is automatic in the sense that arrays and objects own their values, and when the array or object is freed, all data in it is freed as well.

Typical use would be:

Var O : TJSONObject; begin O:=TJSONObject.Create(['Age',44, 'Firstname','Michael', 'Lastname','Van Canneyt']); Writeln(O.AsJSON); Write('Welcome ',O.Strings['Firstname'],', '); Writeln(O.Get('Lastname','')); // empty default. Writeln(', your current age is ',O.Integers('Age']); O.Free; end;

The TJSONArray and TJSONObject classes offer methods to examine, get and set the various members and search through the various members.

Currently the JSON support only allows the use of UTF-8 data.

Parsing incoming JSON and constructing the JSON data structures is not implemented in the fpJSON unit. For this, the unit must be included in the program unit clause. This sets several callback hooks (using and then the function can then be used to transform a string or stream to JSON data structures:

uses fpjson, jsonparser; Var D,E : TJSONData; begin D:=GetJSON('{ "Children" : ['+ ' { "Age" : 23, '+ ' "Names" : { "LastName" : "Rodriquez",'+ ' "FirstName" : "Roberto" }},'+ ' { "Age" : 20,'+ ' "Names" : { "LastName" : "Rodriquez",'+ ' "FirstName" : "Maria" }}'+ ' ]}'); E:=D.FindPath('Children[1].Names.FirstName'); Writeln(E.AsJSON); end.

will print "Maria".

The FPJSON code does not use hardcoded class names when creating the JSON: it uses the various functions to create the data. These functions use a registry of classes, so it is possible to create descendents of the classes in the fpjson unit and have these used for construction of JSON Data structures. The and functions can be used to get or set the classes that must be used. the default parser used by will also use these functions.

Possible types of JSON data TJSONtype determines the type of JSON data a particular object contains. The class function returns this type, and indicates what kind of data that particular descendent contains. The values correspond to the original data types in the JSON specification. The TJSONData object itself returns the unknown value. Unknown JSON data type Numerical type. This can be integer (32/64 bit) or float. String data type. Boolean data Null data Array data (integer index,elements can be any type) Object data (named index, elements can be any type) Float type used in JSON unit TJSONFloat is the floating point type used in the JSON support. It is currently a double, but this can be changed easily. String type used in JSON unit TJSONFloat is the string point type used in the JSON support. It is currently an ansistring, but this can be changed easily. Unicode characters can be encoded with UTF-8. Character type used in parsing TJSONCharType is the type of a single character in a string. It is used by the parser. Pointer to TJSONCharType, used in parsing PJSONCharType is a pointer to a character. It is used while parsing JSON. Formatting options for FormatJSON TFormatOption enumerates the various formatting options that can be used in the function. Keep all array elements on a lingle line. Keep all object elements on a single line. Do not use quote characters around object member names. Use the tabulator character for indents Set of TFormatOption options. TFormatOptions is the set definition used to specify options in . Default indent size for formatted JSON DefaultIndentSize is the default indent size used in formatted JSON. Default formatting options DefaultFormat contains the default formatting options used in formatted JSON. Formatting options to reproduce JSON AsJSONFormat contains the options that make behave like Base (abstract) object for all JSON based data types

TJSONData is an abstract class which introduces all properties and methods needed to work with JSON-based data. It should never be instantiated. Based on the type of data that must be represented one of the following descendents must be instantiated instead.

Numbers
must be represented using one of , or , depending on the type of the number.
Strings
can be represented with .
Boolean
can be represented withn .
null
is supported using
Array
data can be represented using
Object
data can be supported using

To handle arbitrary data, a variable of type TJSONData can be declared, and it can be used to handle any of the above. The property can be read to get a JSON representation of the data.

Create a new instance of TJSONData. Create instantiates a new TJSONData object. It should never be called directly, instead one of the descendents should be instantiated. The native JSON data type represented by this object JSONType indicates the JSON data type that this object will be written as, or the JSON data type that instantiated this object. In TJSONData, this function returns jtUnknown. Descendents override this method to return the correct data type. The native JSON data type Clear the raw value of this data object Clear is implemented by the descendents of TJSONData to clear the data. An array will be emptied, an object will remove all properties, numbers are set to zero, strings set to the empty string, etc. Duplicate the value of the JSON data

Clone returns a new instance of the TJSONData descendent that has the same value as the instance, i.e. the AsJSON property of the instance and its clone is the same.

Note that the clone must be freed by the caller. Freeing a JSON object will not free its clones.

Normally, no JSON-specific errors should occur, but an EOutOfMemory exception can be raised.
A new instance with the same JSON representation Return a formatted JSON representation of the data.

FormatJSON returns a formatted JSON representation of the data. For simple JSON values, this is the same representation as the property, but for complex values ( and ) the JSON is formatted differently.

There are some optional parameters to control the formatting. Options controls the use of whitespace and newlines. IndentSize controls the amount of indent applied when starting a new line.

The implementation is not optimized for speed.

The JSON representation of the instance. Formatting options to apply Amount of indent to use when starting new lines. Number of sub-items for this data element Count is the amount of members of this data element. For simple values (null, boolean, number and string) this is zero. For complex structures, this is the amount of elements in the array or the number of properties of the object Indexed access to sub-items Items allows indexed access to the sub-items of this data. The Index is 0-based, and runs from 0 to Count-1. For simple data types, this function always returns Nil, the complex data type descendents ( and ) override this method to return the Index-th element in the list. The index in the array The value of this data object as a variant.

Value returns the value of the data object as a variant when read, and converts the variant value to the native JSON type of the object. It does not change the native JSON type (), so the variant value must be convertable to the native JSON type.

For complex types, reading or writing this property will raise an EConvertError exception.

Access the raw JSON value as a string

AsString allows access to the raw value as a string. When reading, it converts the native value of the data to a string. When writing, it attempts to transform the string to a native value. If this conversion fails, an EConvertError exception is raised.

For this will return the native value.

For complex values, reading or writing this property will result in an EConvertError exception.

Access the raw JSON value as a float

AsFloat allows access to the raw value as a floating-point value. When reading, it converts the native value of the data to a floating-point. When writing, it attempts to transform the floating-point value to a native value. If this conversion fails, an EConvertError exception is raised.

For this will return the native value.

For complex values, reading or writing this property will always result in an EConvertError exception.

Access the raw JSON value as an 32-bit integer

AsInteger allows access to the raw value as a 32-bit integer value. When reading, it attempts to convert the native value of the data to a 32-bit integer value. When writing, it attempts to transform the 32-bit integer value to a native value. If either conversion fails, an EConvertError exception is raised.

For this will return the native value.

For complex values, reading or writing this property will always result in an EConvertError exception.

Access the raw JSON value as an 64-bit integer

AsInt64 allows access to the raw value as a 64-bit integer value. When reading, it attempts to convert the native value of the data to a 64-bit integer value. When writing, it attempts to transform the 64-bit integer value to a native value. If either conversion fails, an EConvertError exception is raised.

For this will return the native value.

For complex values, reading or writing this property will always result in an EConvertError exception.

Access the raw JSON value as a boolean

AsBoolean allows access to the raw value as a boolean value. When reading, it attempts to convert the native value of the data to a boolean value. When writing, it attempts to transform the boolean value to a native value. For numbers this means that nonzero numbers result in True, a zero resutls in False. If either conversion fails, an EConvertError exception is raised.

For this will return the native value.

For complex values, reading or writing this property will always result in an EConvertError exception.

Is the data a null value ? IsNull is True only for JSONType=jtNull, i.e. for a instance. In all other cases, it is False. This value cannot be set. Return a JSON representation of the value AsJSON returns a JSON representation of the value of the data. For simple values, this is just a textual representation of the object. For objects and arrays, this is an actual JSON Object or array. Class of TJSONData TJSONDataClass is used in the , and functions to set the actual classes used when creating JSON data. Enumerate the different kind of numerical types TJSONNumberType is used to enumerate the different kind of numerical types: JSON only has a single 'number' format. Depending on how the value was parsed, FPC tries to create a value that is as close to the original value as possible: this can be one of integer, int64 or TJSONFloatType (normally a double). The number types have a common ancestor, and they are distinguished by their value. Floating point value 32-bit Integer value 64-bit integer value Common ancestor for the numerical value JSON classes. TJSONNumber is an abstract class which serves as the ancestor for the 3 numerical classes. It should never be instantiated directly. Instead, depending on the kind of data, one of , or should be instantiated. native JSON data type JSONType is overridden by TJSONNumber to return jtNumber. Always jtNumber Kind of numerical data managed by this class. NumberType is overridden by TJSONNumber descendents to return the kind of numerical data that can be managed by the class. the kind of numerical data managed by this class. Class to represent floating-point JSON data. TJSONFloatNumber must be used whenever floating point data must be represented. It can handle data (normally a double). For integer data, or are better suited. Create a new floating-point value Create instantiates a new JSON floating point value, and initializes it with AValue. Initial floating point value Kind of numerical data managed by this class. NumberType is overridden by TJSONFloatNumber to return ntFloat. Always ntFloat Clear value Clear is overridden by TJSONFloatNumber to set the value to 0.0 Clone floating point value Clone overrides and creates an instance of the same class with the same floating-point value. New instance of TJSONFloatNumber with the same value Class to represent 32-bit integer JSON data. TJSONIntegerNumber must be used whenever 32-bit integer data must be represented. For 64-bit integer data, must be used. Create a new instance of 32-bit integer JSON data Create instantiates a new 32-bit integer JSON data and initializes the value with AValue. Initial value for the integer data Kind of numerical data managed by this class. NumberType is overridden by TJSONIntegerNumber to return ntInteger. Always ntInteger Clear value Clear is overridden by TJSONIntegerNumber to set the value to 0. Clone 32-bit integer value Clone overrides and creates an instance of the same class with the same 32-bit integer value. New instance of TJSONIntegerNumber with the same integer value Class to represent 64-bit integer JSON data. TJSONInt64Number must be used whenever 64-bit integer data must be represented. For 32-bit integer data, must be used. Create a new instance of 64-bit integer JSON data Create instantiates a new 64-bit integer JSON data and initializes the value with AValue. Initial 64-bit integer value Kind of numerical data managed by this class. NumberType is overridden by TJSONInt64Number to return ntInt64. Always ntInt64 Clear value Clear is overridden by TJSONInt64Number to set the value to 0. Clone 64-bit integer value Clone overrides and creates an instance of the same class with the same 64-bit integer value. New instance of TJSONIntegerNumber with the same int64 value Class to represent string JSON data. TJSONString must be used whenever string data must be represented. Currently the implementation uses an ansi string to hold the data. This means that to correctly hold unicode data, a UTF-8 encoding must be used. Create a new instance of string JSON data Create instantiates a new string JSON data and initializes the value with AValue. Currently the implementation uses an ansi string to hold the data. This means that to correctly hold unicode data, a UTF-8 encoding must be used. Initial string value. native JSON data type JSONType is overridden by TJSONString to return jtString. Always jtString Clear value Clear is overridden by TJSONString to set the value to the empty string ''. Clone string value Clone overrides and creates an instance of the same class with the same string value. New instance of TJSONString with the same string value Class to represent boolean JSON data. TJSONBoolean must be used whenever boolean data must be represented. It has limited functionality to convert the value from or to integer or floating point data. Create a new instance of boolean JSON data Create instantiates a new boolean JSON data and initializes the value with AValue. Initial boolean value native JSON data type JSONType is overridden by TJSONString to return jtBoolean. Always jtBoolean Clear data Clear is overridden by TJSONBoolean to set the value to False. Clone boolean value Clone overrides and creates an instance of the same class with the same boolean value. New instance of TJSONBoolean with the same boolean value Class to represent boolean JSON data. TJSONNull must be used whenever a null value must be represented. native JSON data type JSONType is overridden by TJSONNull to return jtNull. Always jtNull Clear data Clear does nothing. Clone boolean value Clone overrides and creates an instance of the same class. New instance of TJSONNull Iterator callback for TJSONArray.Iterate TJSONArrayIterator is the procedural callback used by to iterate over the values. Item is the current item in the iteration. Data is the data passed on when calling Iterate. The Continue parameter can be set to false to stop the iteration loop. Current item extra data Continue iterating or not ? Class to represent array data

TJSONArray is the class that must be used to represent array data. In difference with pascal arrays, the array elements can be of any valid JSON data type. It is similar to a TObjectList in that the memory management is automatic: the array grows and shrinks to accomodate the number of element in it. The elements in the array are owned by the array, so they should not be freed.

The array can be created empty or can be created with a series of values that will be converted to JSON objects and added to the initial JSON array.

The items in the array are available as raw JSON objects in the property. The data can also be accessed (read-write) as native Pascal types through the , , etc. array properties. The actual JSON types are available in the array.

Elements can be added to the array using the various forms of the and methods. Elements can be deleted with the method.

Create a new instance of JSON array data.

Create creates a new JSON array instance, and initializes the data with Elements. The elements are converted to various instances, instances of TJSONData are inserted in the array as-is.

The data type of the inserted objects is determined from the type of data passed to it, with a natural mapping. A Nil pointer will be inserted as a TJSONNull value.

If an invalid class or not recognized data type (pointer) is inserted in the elements array, an EConvertError exception will be raised.
Data to add to the array. Free the JSON array Destroy will delete all elements in the array and clean up the instance. native JSON data type JSONType is overridden by TJSONArray to return jtArray. Alway jtArray Clone the JSON array Clone creates a new TJSONArray, clones all elements in the array and adds them to the newly created array in the same order as they are in the array. Cloned TJSONArray instance. Iterate over all elements in the array Iterate iterates over all elements in the array, passing them one by one to the Iterator callback, together with the Data parameter. The iteration stops when all elements have been passed or when the iterator callback returned False in the Continue parameter. Iterator callback, called for each element in the array. Data item passed to the iterator with each call. Return index of JSONData instance in array IndexOf compares all elements in the array with Obj and returns the index of the element instance that equals Obj. The actual instances are compared, not the JSON value. If none of the elements match, the function returns -1. Index of Obj in the array, or -1. Object instance to search for. Clear the array Clear clears the array and frees all elements in it. After the call to clear, Count returns 0. Add a JSON value to the array

Add adds the value passed on to the array. If it is a plain pascal value, it is converted to an appropriate instance. If a TJSONData instance is passed, it is simply added to the array. Note that the instance will be owned by the array, and destroyed when the array is cleared (this is in particular true is an JSON array or object).

The function returns the TJSONData instance that was added to the array.

TJSONData instance that was added. TJSONData instance to add to array. Integer value to add to array String value to add to array Floating point value to add to array Boolean value to array JSON Array to add to array. JSON Object to add to array. Delete an element from the list by index Delete deletes the element with given Index from the list. The element is freed. If an invalid index is passed, an exception is raised. Index of the element to delete. Exchange 2 elements in the list Exchange exchanges 2 elements at locations Index1 and Index2 in the list. This is more efficient than manually extracting and adding the elements to the list. If an invalid index (for either element) is passed, an exception is raised. Index of the first element Index of the second element. Extract an element from the array Extract removes the element at position Index or the indicated element from the list, just as does. In difference with Delete, it does not free the object instance. Instead, it returns the extracted element. Extracted element Item to extract from the array Index of item to extract from the array Insert an element in the array.

Insert adds a value or element to the array at position Index. Elements with index equal to or larger than Index are shifted. Like , it converts plain pascal values to JSON values.

Note that when inserting a instance to the array, it is owned by the array. Index must be a value between 0 and Count-1.

If an invalid index is specified, an exception is raised.
Position at which to insert the new value JSON Data object to insert. Integer value to insert String value to insert Floating point value to insert Boolean value to insert JSON array to insert. JSON Object to insert Move a value from one location to another Move moves the element at index CurIndex to the position NewIndex. It will shift the elements in between as needed. This operation is more efficient than extracting and inserting the element manually. Current index of the element Final index of the element. Remove an element from the list Remove removes item from the array, if it is in the array. The object pointer is checked for presence in the array, not the JSON values. Note that the element is freed if it was in the array and is removed. Item to remove from the array Indexed access to the values in the array Items is introduced in . TJSONArray simply declares it as the default property. JSON types of elements in the array

Types gives direct access to the result of the elements in the array. Accessing it is equivalent to accessing

Items[Index].JSONType
Index of element whose type must be read Check which elements are null

Nulls gives direct access to the property when reading. It is then equivalent to accessing

Items[Index].IsNull
Element to check for null value Get or set elements as integer values

Integers gives direct access to the property when reading. Reading it is the equivalent to accessing

Items[Index].AsInteger

When writing, it will check if an integer JSON value is located at the given location, and replace it with the new value. If a non-integer JSON value is there, it is replaced with the written integer value.

Index of element to read or write Get or set elements as Int64 values

Int64s gives direct access to the property when reading. Reading it is the equivalent to accessing

Items[Index].AsInt64

When writing, it will check if an 64-bit integer JSON value is located at the given location, and replace it with the new value. If a non-64-bit-integer JSON value is there, it is replaced with the written int64 value.

Index of element to read/write Get or set elements as string values

Strings gives direct access to the property when reading. Reading it is the equivalent to accessing

Items[Index].AsString

When writing, it will check if a string JSON value is located at the given location, and replace it with the new value. If a non-string value is there, it is replaced with the written string value.

Index of element to read/write Get or set elements as floating-point numerical values

Floats gives direct access to the property when reading. Reading it is the equivalent to accessing

Items[Index].AsFloat

When writing, it will check if a floating point numerical JSON value is located at the given location, and replace it with the new value. If a non-floating point numerical value is there, it is replaced with the written floating point value.

Index of element to read/write Get or set elements as boolean values

Floats gives direct access to the property when reading. Reading it is the equivalent to accessing

Items[Index].AsBoolean

When writing, it will check if a boolean JSON value is located at the given location, and replace it with the new value. If a non-boolean value is there, it is replaced with the written boolean value.

Index of element to read/write Get or set elements as JSON array values

Arrays gives direct access to JSON Array values when reading. Reading it is the equivalent to accessing

Items[Index] As TJSONArray

When writing, it will replace any previous value at that location with the witten value. Note that the old value is freed, and the new value is owned by the array.

Index of element to read/write Get or set elements as JSON object values

Objects gives direct access to JSON object values when reading. Reading it is the equivalent to accessing

Items[Index] As TJSONObject

When writing, it will replace any previous value at that location with the witten value. Note that the old value is freed, and the new value is owned by the array.

Index of element to read/write Iterator callback for TJSONObject.Iterate TJSONObjectIterator is the procedural callback used by to iterate over the values. Item is the current item in the iteration, and AName it's name. Data is the data passed on when calling Iterate. The Continue parameter can be set to false to stop the iteration loop. Name (key) of the current item in the object Current item Data passed on to Iterate call Set to false to stop the iteration Class to represent a JSON object literal

TJSONObject is the class that must be used to represent a JSON object literal. It can be compared to a dictionary class or a list class in which the list index is a string value, or indeed a proper class with an arbitrary number of properties. The elements can be of any valid JSON data type. The memory management is automatic: the object grows and shrinks to accomodate the number of elements (properties) in it. The elements in the array are owned by the object, so they should not be freed.

The object can be created empty or can be created with a series of named values that will be converted to JSON objects and added to the initial JSON array.

The items in the object are available with a numerical index as raw JSON objects in the and with their names in the property. The data can also be accessed (read-write) as native Pascal types through the , , etc. array properties, using their name as a key. The actual JSON types are available in the array.

Elements can be added to the array using the various forms of the method. Elements can be deleted with the method.

Create a new instance of JSON object data.

Create creates a new JSON object instance, and initializes the data with Elements. Elements is an array containing an even number of items, alternating a name and a value. The names must be strings, and the values are converted to various instances. If a value is an instance of TJSONData, it is added to the object array as-is.

The data type of the inserted objects is determined from the type of data passed to it, with a natural mapping. A Nil pointer will be inserted as a TJSONNull value. The following gives an example:

Var O : TJSONObject; begin O:=TJSONObject.Create(['Age',44, 'Firstname','Michael', 'Lastname','Van Canneyt']);

An EConvertError exception is raised in one of the following cases:

  1. If an odd number of arguments is passed
  2. an item where a name is expected does not contain a string
  3. A value contains an invalid class
  4. A value of a not recognized data type (pointer) is inserted in the elements
Names and corresponding values to be added to the object Free the JSON object Destroy will delete all elements in the array and clean up the instance. native JSON data type JSONType is overridden by TJSONObject to return jtObject. Always jtObject Clone the JSON object Clone creates a new TJSONObject, clones all elements in the array and adds them to the newly created array with the same names as they were in the array. Cloned TJSONObject instance. Iterate over all elements in the object Iterate iterates over all elements in the object, passing them one by one with name and value to the Iterator callback, together with the Data parameter. The iteration stops when all elements have been passed or when the iterator callback returned False in the Continue parameter. Iterator callback, called for each element in the array. Data item passed to the iterator with each call. Return index of JSONData instance in object IndexOf compares all elements in the object with Obj and returns the index (in the property) of the element instance that equals Obj. The actual instances are compared, not the JSON value. If none of the elements match, the function returns -1. Index of Obj in the array, or -1. Object instance to search for. Return index of name in item list

IndexOfName compares the names of all elements in the object with AName and returns the index (in the property) of the element instance whose name matched AName. If none of the element's names match, the function returns -1.

Since JSON is a case-sensitive specification, the names are searched case-sensitively by default. This can be changed by setting the optional CaseInsensitive parameter to True

Index of AName in the array, or -1. Name to search for. Search case-insensitively or not ? Find an element by name.

Find compares the names of all elements in the object with AName and returns the matching element. If none of the element's names match, the function returns Nil

Since JSON is a case-sensitive specification, the names are searched case-sensitively.

If AType is specified then the element's type must also match the specified type.

Data element corresponding to AName Name to search for. Type to match. Retrieve a value by name

Get can be used to retrieve a value by name. If an element with name equal to AName exists, and its type corresponds to the type of the ADefault, then the value is returned. If no element element with the correct type exists, the ADefault value is returned.

If no default is specified, the value is returned as a variant type, or Null if no value was found.

The other value retrieval properties such as , , , , , will raise an exception if the name is not found. The Get function does not raise an exception.

The requested value Name of the value to retrieve Default value to return if no value is found or it has the wrong type. Clear the object Clear clears the object and frees all elements in it. After the call to Clear, Count returns 0. Add a name, value to the object

Add adds the value AValue with name AName to the object. If the value is not a descendent, then it is converted to a TJSONData value, and it returns the TJSONData descendent that was created to add the value.

The properties , , , , and will not raise an exception if an existing name is used, they will overwrite any existing value.

If a value with the same name already exists, an exception is raised.
The resulting TJSONData descendent Name to add the value with. Value to add to the object. Delete an element from the list by index Delete deletes the element with given Index or AName from the list. The element is freed. If a non-existing name is specified, no value is deleted. If an invalid index is passed, an exception is raised. Index of element in Items to delete. Name of element to delete Remove item by instance Remove will locate the value Item in the list of values, and removes it if it exists. The item is freed. Item to remove. Extract an element from the object Extract removes the element at position Index or with the AName from the list, just as does. In difference with Delete, it does not free the object instance. Instead, it returns the extracted element. The result is Nil if a non-existing name is specified. Element to extract from the object Index of element to extract Name of element to extract Indexed access to the names of elements. Names allows to retrieve the names of the elements in the object. The index is zero-based, running from 0 to Count-1. Index of name to retrieve. Name-based access to JSON values in the object. Elements allows to retrieve the JSON values of the elements in the object by name. If a non-existent name is specified, an exception is raised. Name of value to retrieve. Types of values in the object. Types allows to retrieve the JSON types of the elements in the object by name. If a non-existent name is specified, an exception is raised. Name of value to retrieve. Named access to null values Nulls allows to retrieve or set the NULL values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by a null value. Name of null value to retrieve Named access to float values Floats allows to retrieve or set the float values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by the specified floating-point value. Name of float value Named access to integer values Integers allows to retrieve or set the integer values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by the specified integer value. Name of integer value Named access to int64 values Int64s allows to retrieve or set the int64 values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by the specified int64 value. Name of int64 value Named access to string values Strings allows to retrieve or set the string values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by the specified string value. Name of string value Named access to boolean values Booleans allows to retrieve or set the boolean values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by the specified boolean value. Name of boolean value Named access to JSON array values Arrays allows to retrieve or set the JSON array values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by the specified JSON array. Name of JSON array value Named access to JSON object values Objects allows to retrieve or set the JSON object values in the object by name. If a non-existent name is specified, an exception is raised when reading. When writing, any existing value is replaced by the specified JSON object. Name of JSON object value JSON exception EJSON is the exception raised by the JSON implementation to report JSON error. Convert a string to a JSON-escaped string

StringToJSONString examines the string S and replaces any special characters by an escaped string, as in the JSON specification. The following characters are escaped:

\ / "  #8 #9 #10 #12 #13.
properly escaped JSON string String to convert to JSON string. Convert a JSON-escaped string to a string

JSONStringToString examines the string S and replaces any special characters by an escaped string, as in the JSON specification. The following escaped characters are recognized:

\\ \" \/ \b \t \n \f \r \u000X
Pascal string with escaped characters replaced JSON-escaped string to convert. Convert a JSON type to a string JSONTypeName converts the JSONType to a string that describes the type of JSON value. Name of JSON type JSON type to convert to a string Type of instance to create TJSONInstanceType is used by the parser to determine what kind of descendent to create for a particular data item. It is a more fine-grained division than Unknown 32-bit signed integer number value 64-bit signed integer number value Floating point real number value String value Boolean value Null value Array value Object value JSON enumerator loop variable type TJSONEnum is the loop variable type to use when implementing a JSON enumerator (for in). It contains 3 elements which are available in the loop: key, keynum (numerical key) and the actual value (TJSONData). String Key value Numerical key value Actual value JSON enumerator

TBaseJSONEnumerator is the base type for the JSON enumerators. It should not be used directly, instead use the enumerator support of Object pascal to loop over values in JSON data.

The value of the TBaseJSONEnumerator enumerator is a record that describes the key and value of a JSON value. The key can be string-based (for records) or numerical (for arrays).

Return the current value of the enumerator GetCurrent returns the current value of the enumerator. This is a value. Current TJSONEnum value Move to next value in array/object MoveNext attempts to move to the next value. This will return True if the move was succesful, or False if not. When True is returned, then True if the move was succesful Return the current value of the enumerator Current returns the current enumerator value of type . It is only valid after returned True. Return an enumerator for the data GetEnumerator returns an enumerator for the JSON data. For simple types, the enumerator will just contain the current value. For arrays and objects, the enumerator will loop over the values in the array. The return value is not a type, but a structure, which contains the value, and for structured types, the key (numerical or string). The new enumerator Find data by name

FindPath finds a value based on its path. If none is found, Nil is returned. The path elements are separated by dots and square brackets, as in object member notation or array notation. The path is case sensitive.

  • For simple values, the path must be empty.
  • For objects, a member can be specified using its name, and the object value itself can be retrieved with the empty path.
  • For Arrays, the elements can be found based on an array index. The array value itself can be retrieved with the empty path.

The following code will return the value itself, i.e. E will contain the same element as D:

Var D,E : TJSONData; begin D:=TJSONIntegerNumber.Create(123); E:=D.FindPath(''); end.

The following code will not return anything:

Var D,E : TJSONData; begin D:=TJSONIntegerNumber.Create(123); E:=D.FindPath('a'); end.

The following code will return the third element from the array:

Var D,E : TJSONData; begin D:=TJSONArray.Create([1,2,3,4,5]); E:=D.FindPath('[2]'); Writeln(E.AsJSON); end.

The output of this program is 3.

The following code returns the element Age from the object:

Var D,E : TJSONData; begin D:=TJSONObject.Create(['Age',23, 'Lastame','Rodriguez', 'FirstName','Roberto']); E:=D.FindPath('Age'); Writeln(E.AsJSON); end.

The code will print 23.

Obviously, this can be combined:

Var D,E : TJSONData; begin D:=TJSONObject.Create(['Age',23, 'Names', TJSONObject.Create([ 'LastName','Rodriguez', 'FirstName','Roberto'])]); E:=D.FindPath('Names.LastName'); Writeln(E.AsJSON); end.

And mixed:

var D,E : TJSONData; begin D:=TJSONObject.Create(['Children', TJSONArray.Create([ TJSONObject.Create(['Age',23, 'Names', TJSONObject.Create([ 'LastName','Rodriguez', 'FirstName','Roberto']) ]), TJSONObject.Create(['Age',20, 'Names', TJSONObject.Create([ 'LastName','Rodriguez', 'FirstName','Maria']) ]) ]) ]); E:=D.FindPath('Children[1].Names.FirstName'); Writeln(E.AsJSON); end.
The found data element, or nil Path to search for Get data by name GetPath is identical to but raises an exception if no element was found. The exception message contains the piece of path that was not found. An exception is raised if the path does not exist. The found data element The path of the data element to retrieve. Class of TJSONFloatNumber TJSONFloatNumberClass is the class type of . It is used in the factory methods. Class of TJSONIntegerNumber TJSONIntegerNumberClass is the class type of . It is used in the factory methods. Class of TJSONInt64Number TJSONInt64NumberClass is the class type of . It is used in the factory methods. Class of TJSONString TJSONStringClass is the class type of . It is used in the factory methods. Class of TJSONBoolean TJSONBooleanClass is the class type of . It is used in the factory methods. Class of TJSONNull TJSONNullClass is the class type of . It is used in the factory methods. Get an array enumerator GetEnumerator is overridden in TJSONarray so it returns an array enumerator. The array enumerator will return all the elements in the array, and stores their index in the KeyNum member of . The array enumerator Class of TJSONArray TJSONArrayClass is the class type of . It is used in the factory methods. Get an object enumerator GetEnumerator is overridden in TJSONObject so it returns an object enumerator. The array enumerator will return all the elements in the array, and stores their name in the Key and index in the KeyNum members of . The object enumerator Class of TJSONObject TJSONObjectClass is the class type of . It is used in the factory methods. Callback to to parse JSON into JSONData

TJSONParserHandler is a callback prototype used by the function to do the actual parsing. It has 2 arguments: AStream, which is the stream containing the JSON that must be parsed, and AUseUTF8, which indicates whether the (ansi) strings contain UTF-8.

The result should be returned in Data.

The parser is expected to use the JSON class types registered using the method, the actual types can be retrieved with

Stream to parse. Use UTF-8 in returned ansistrings Resulting JSON data. JSON factory: Set the JSONData class types to use

SetJSONInstanceType can be used to register descendents of the class, one for each possible kind of data. The class type used to instantiate data of type AType is passed in AClass.

The JSON parser will use the registered types to instantiate JSON Data instanced: when the parser encounters a value of type AType, it will instantiate a class of type AClass. By default, the classes in the fpJSON unit are used.

The functions also use the types registered here to instantiate their data.

If AClass is not suitable to contain data of type AType, an exception is raised.
Type of data to register a class for Class to use when a data item of type AType is encountered. JSON factory: Get the JSONData class types to use

GetJSONInstanceType can be used to retrieve the registered descendents of the class, one for each possible kind of data. The result is the class type used to instantiate data of type AType.

The JSON parser and the function will use the registered types to instantiate JSON Data. When the parser encounters a value of type AType, it will instantiate a class of the type returned by this function. By default, the classes in the fpJSON unit are returned.

The class to instantiate for data of type AType Data type for which to return the class. Create a JSON data item

CreateJSON will create a JSON Data item depending on the type of data passed to it, and will use the classes returned by to do so. The classes to be used can be set using the .

The JSON parser uses these functions to create instances of .

None.
The TJSONData descendant representing the value in Data The data to create as a JSON data item. Create a JSON array CreateJSONArray retrieves the class registered to represent JSON array data, and creates an instance of this class, passing Data to the constructor. For the Data array the same type conversion rules as for the constructor apply. if one of the elements in Data cannot be converted to a JSON structure, an exception will be raised. The TJSONArray instance representing Data Data to include in the array. Create a JSON object CreateJSONObject retrieves the class registered to represent JSON object data, and creates an instance of this class, passing Data to the constructor. For the Data array the same type conversion rules as for the constructor apply. if one of the elements in Data cannot be converted to a JSON structure, an exception will be raised. The TJSONObject instance representing Data Data as (name, value) pairs to create a JSON object from Convert JSON string to JSON data structure

GetJSON will read the JSON argument (a string or stream that contains a valid JSON data representation) and converts it to native JSON objects. The stream must be positioned on the start of the JSON.

The fpJSON unit does not contain a JSON parser. The jsonparser unit does contain a JSON parser, and must be included once in the project to be able to parse JSON. The jsonparser unit uses the call to set a callback that is used by GetJSON to parse the data.

If UseUTF8 is set to true, then unicode characters will be encoded as UTF-8. Otherwise, they are converted to the nearest matching ansi character.

An exception will be raised if the JSON data stream does not contain valid JSON data.
The TJSONData data (tree) represented by JSON The JSON to parse. Convert unicode characters to UTF-8 Set the JSON parser handler

SetJSONParserHandler can be used to set the JSON parser handler callback. The fpJSON unit does not contain a JSON parser in itself: it contains simply the data structure and the ability to write JSON. The parsing must be done using a separate unit, and is invoked through a callback. SetJSONParserHandler must be used to set this callback.

The jsonparser unit does contain a JSON parser, and must be included once in the project to be able to parse JSON. The jsonparser unit uses the SetJSONParserHandler call to set the callback that is used by GetJSON to parse the data. This is done once at the initialization of that unit, so it is sufficient to include the unit in the uses clause of the program.

The new value for the handler Get the current JSON parser handler

GetJSONParserHandler can be used to get the current value of the JSON parser handler callback.

The fpJSON unit does not contain a JSON parser in itself: it contains simply the data structure and the ability to write JSON. The parsing must be done using a separate unit.

The current parser callback value