---
url: /statelake/scripting-reference/json-for-scripts/creating-json-objects.md
---

# Creating JSON Objects

There are two ways of creating a JSON entity. They can be either constructed from a blank object or deserialized (parsed) from an existing JSON string with data.

## Creating A Blank JSON Object

To create an empty JSON object or array, you can use the constructors of these types as follows:

```pascal
var
    obj: TJSONObject;
    arr: TJSONArray;
begin
    obj := TJSONObject.Create;
    arr := TJSONArray.Create;
    …
    obj.Free;
    arr.Free;
end;
```

In the sample code, two JSON entities of different types (object and array) are created. Since these objects are allocated in the heap memory by using the class constructors, we have to release the memory afterwards once we finish working with the objects.

A JSON entity of a specific type such as **TJSONObject**, **TJSONArray**, **TJSONString** and etc. can be stored as a common **TJSONValue** due to the polymorphism nature of the classes:

```pascal
var
 val: TJSONValue;
begin
 val := TJSONObject.Create as TJSONValue;
 val.Free;
 val := TJSONString.Create(‘Hello World’) as TJSONValue;
 val.Free;
end;
```

Operator **as** can be used to perform upcasting from a specific JSON type to a common JSON value type.

## Creating A Prefilled JSON Value

If we have an input JSON string, we can parse it into a tree of JSON entities using the special constructor of **TJSONValue**:

```pascal
var
    obj: TJSONObject;
begin
    obj := TJSONValue.Parse(‘{“key”: ”value”}’) as TJSONObject;
 if obj <> nil then
 begin
 // The object has been parsed successfully
        …
 end;
    obj.Free;
end;
```

**TJSONValue.Parse** returns a **TJSONValue** instance. However, we can downcast it to a specific type, if we know the type. In the example we downcast it to **TJSONObject**. If we don’t know the type, we can put the value into a **TJSONValue** variable and then test it using methods **IsObject**, **IsArray** and etc. (see “Checking types of JSON values” section).

We can also pass a string variable obtained from any kind of source into the JSON value constructor:

```pascal
var
    s: string;
    obj: TJSONObject;
begin
    s := SourceDataset[‘somefield’].AsString;
    obj := TJSONValue.Parse(s) as TJSONObject;
    …
    obj.Free;
end;
```

**Remember**: If a JSON string has not been parsed successfully due to any syntax errors, the result of the **TJSONValue.Parse** function will be **nil**.
