as_json¶
The as_json filter serializes Experience Builder values (objects, arrays, or primitive types) into a JSON string. This is crucial for data interchange, making your template's data easily consumable by external systems or JavaScript components.
Functionality
- Experience Builder Values: Takes any valid Experience Builder value as input (numbers, strings, booleans, arrays, dictionaries, objects, dates, etc.).
- Serialization: Converts the input value into its JSON representation, following standard JSON rules.
- Output: Returns a string containing the JSON-encoded data.
Syntax
Arguments
The as_json filter does not require any arguments. However, it optionally supports a single argument that indicates whether or not the output should be indented for readability:
If the argument is omitted, the default behavior is to produce unformatted JSON.
Code Samples
Example 1: Serializing a Simple Object
Output:Example 2: Serializing an Array
Output:
Example 3: Pretty-Printed JSON
{% assign data = { items: [{name: "Widget A", price: 9.99}, {name: "Widget B", price: 14.95}] } %}
{{ data | as_json: true }}
Output:
Outliers and Special Cases¶
- Circular References: The filter attempts to detect circular references (objects that refer to themselves) and replaces them with an error message.
- Unsupported Types: If the input value contains types that cannot be directly represented in JSON (e.g., custom objects with unsupported properties), the filter might omit those values or convert them to strings.
Key Points¶
- The
as_jsonfilter is indispensable for working with APIs, passing data to JavaScript, or storing structured data in a format that is easy to read and parse. - It automatically handles complex structures like nested arrays and objects.
- Be aware of potential issues with circular references.
- Consider using the optional formatting argument to make the JSON output easier to read.