Adding Or Updating Children Of TJSONObject

To add or update a child of a JSON object you can use the square brackets operator:

Object[‘key’] := SomeJSONValue;

Make sure the passed value is a TJSONValue. For example, if you want to put a string field into a JSON object, you need to create a TJSONString object and upcast it to TJSONValue:

Object[‘key’] := TJSONString.Create(‘Hello World’) as TJSONValue;

Remember: Once you enclosed one TJSONValue into another, the enclosed object will belong to its new owner, which means that Free method of the owner will take care of releasing the enclosed TJSONValue object memory.

If the value already exists by the specified key, it’s recommended to remove it and release its memory first. (see “Removing Children From TJSONObject”)

You can enclose JSON objects into each other following the same approach:

var
ParentObject, ChildObject: TJSONObject;
begin
ParentObject := TJSONObject.Create;
ChildObject := TJSONObject.Create;
ParentObject[‘subobject’] := ChildObject;
ParentObject.Free;
end;

Removing Children From TJSONObject

To remove a child from TJSONObject you can use TJSONObject.Remove method:

Object.Remove(‘key’);

Remember: This method does not release the memory of the removed entity, it only removes a child from a list of children. You can either move the reference to the removed entity into another variable:

var
RemovedValue: TJSONValue;
RemovedValue := Object.Remove(‘key’);

or release its memory straight away as follows:

Object.Remove(‘key’).Free;

Remember: If you ignore the result of Remove method, you will cause a memory leak.

Adding Children To TJSONArray

To add an element to a TJSONArray object you may use the Add method:

Array.Add(Value);

The passed value must be a TJSONValue. For example, if you want to put a string value into a JSON array, you need to create a TJSONString object and upcast it to TJSONValue:

Array.Add(TJSONString.Create(‘Hello World’) as TJSONValue);

var
    Arr: TJSONArray;
begin
    Arr := TJSONArray.Create;
    Arr.Add(TJSONNumber.Create(100) as TJSONValue);
Arr.Add(TJSONNumber.Create(200) as TJSONValue);
Arr.Free;
end;

Removing Children From TJSONArray

To remove an item from a JSON array, you may use the Remove method:

Array.Remove(0);

However, this method does not release the memory of the removed entity, it only removes a child from a list of children. You can either move the reference to the removed entity into another variable:

var
   RemovedValue: TJSONValue;
   …
RemovedValue := Array.Remove(0);

or release its memory straight away as follows:

Array.Remove(0).Free;

Remember: If you ignore the result of Remove method, you will cause a memory leak.