DWScript provides built-in, high-performance JSON support through the JSON object and the JSONVariant type.
| Method | Parameters | Description |
|---|---|---|
Parse |
jsonStr |
Parses JSON string into a JSONVariant. |
Stringify |
value |
Converts a value (Record, Class, Array, etc) to a JSON string. |
PrettyStringify |
value [, indent] |
Formats JSON for readability. |
Serialize |
value |
Converts a native value into a JSONVariant object. |
NewObject / NewArray |
|
Creates a dynamic JSON container. |
DWScript uses a set of consistent rules for automatic serialization via JSON.Stringify:
| Type | Inclusion Rule |
|---|---|
| Classes | Only published fields and properties are included. |
| Named Records | Only published fields are included. |
| Anonymous Records | All fields are automatically included. |
| Arrays | All elements are included as a JSON array. |
type
TUser = class
published
Name : String;
Age : Integer;
private
InternalId : Integer; // Will be ignored
end;
var u := new TUser;
u.Name := 'Alice'; u.Age := 30;
PrintLn(JSON.Stringify(u)); {"Age":30,"Name":"Alice"}Using JSONVariant, you can access keys using dot notation or array indexing.
var data := JSON.Parse('{"items": [10, 20]}');
PrintLn(data.items[0]); 10
When working with JSONVariant, several helper methods are available. Note that these must be called with parentheses () to avoid conflict with JSON field names.
| Method | Returns | Description |
|---|---|---|
Defined() |
Boolean |
Returns True if the value is not Undefined. |
Length() |
Integer |
Returns the number of elements (Array) or keys (Object). |
Low() |
Integer |
Returns the lowest index (usually 0). |
High() |
Integer |
Returns the highest index of an array. |
Add(item) |
Integer |
Appends an item to a JSON array. Returns the new index. |
Push(item) |
Integer |
Alias for Add. |
Delete(id) |
(none) |
Removes an item by index (Array) or key name (Object). |
Swap(i, j) |
(none) |
Swaps two elements in an array. |
Clone() |
JSONVariant |
Returns a deep copy of the structure. |
ToString() |
String |
Returns the JSON string representation. |
TypeName() |
String |
Returns 'Object', 'Array', 'String', 'Number', 'Boolean', 'Null' or 'Undefined'. |
ElementName(i) |
String |
Returns the key name at the given index (for Objects). |
AsInteger / AsFloat |
|
Explicit conversion helpers. |
AsString / AsBoolean |
|
Explicit conversion helpers. |
For high-performance scenarios, these static methods on the JSON object parse strings directly into native Pascal arrays, bypassing JSONVariant overhead.
| Method | Parameters | Returns |
|---|---|---|
ParseIntegerArray |
(jsonStr) |
array of Integer |
ParseFloatArray |
(jsonStr) |
array of Float |
ParseStringArray |
(jsonStr) |
array of String |
DWScript can automatically stringify complex types like Records and Classes. Simply pass the instance to JSON.Stringify.