JSON Field

Last Updated: Jun 17, 2024
documentation for the dotCMS Content Management System

Introduced in version 22.10, the JSON field allows you to store, access, and manipulate semi-structured data within your content in the form of JSON objects.

Screenshot of a JSON field in the user interface, with the editor view toggled.

Adding a JSON Field

You can add a JSON field to a content type in the same ways as any other field, either headlessly or through the user interface:

Screenshot of the JSON Field item from the Content Type editor in the admin panel.

Accessing JSON Data

Note: This section focuses on content objects in Velocity; retrieving the field's data headlessly, such as via a CRUD operation, returns a standard JSON string.

Once you have loaded the field into the Velocity context, either through a built-in content object or a manual content pull, the data is mapped by default, and can be traversed through its keys.

For example, if a URL-mapped content type has a JSON field named jsonField containing the following data, as seen in the screenshot above:

{
    "look":"1",
    "at":2,
    "some":"asdfjkl;",
    "JSON":[
        {
            "data":1234,
            "arranged":"(and how!)"
        },
        "as an example"
    ]
}

The JSON object is accessible by calling the JSON field through the relevant content object — in this example, $URLMapContent.jsonField would be applicable. If called directly, this will return the JSON data in its entirety; to access a data member individually, call the relevant key as an object property.

Here are some examples of calls to data members of the JSON above:

Example CallResult
$URLMapContent.jsonField.someasdfjkl;
$URLMapContent.jsonField.JSON[0]{data=1234, arranged=(and how!)}
$URLMapContent.jsonField.JSON[1]as an example
$URLMapContent.jsonField.JSON[0].data1234

Using the keys as properties is the same as calling the .get() method with that property as the argument. That is, the following two expressions are identical:

  • $URLMapContent.jsonField.look
  • $URLMapContent.jsonField.get("look")

Iterating

Performing a #foreach directive over the JSON field's data object directly will return values only. For example:

<ul>
#foreach ($item in $URLMapContent.jsonField)
    <li>$item</li>
#end
</ul>

This yields:

• 1
• 2
• asdfjkl;
• [{data=1234, arranged=(and how!)}, as an example]

To access the JSON without excluding the keys, instead access the field as a hash table, using the keySet() method. For example:

<ul>
#foreach ($key in $URLMapContent.jsonField.keySet())
    <li>Key: $key / Value: $URLMapContent.jsonField.get($key)</li>
#end
</ul>

The result:

• Key: look / Value: 1
• Key: at / Value: 2
• Key: some / Value: asdfjkl;
• Key: JSON / Value: [{data=1234, arranged=(and how!)}, as an example]

On this page

×

We Dig Feedback

Selected excerpt:

×