Introduction

The json_encode filter converts a variable—such as an array or object—into a JSON-formatted string. This filter is especially useful when you need to pass data from a Twig template to a JavaScript script or an API that consumes JSON.

Example of use

Example of how to use the json_encode filter to convert an array into a JSON string:

{% set order = {number: 12345, customer: 'John Smith', items: ['Product 1', 'Product 2', 'Product 3'], total_value: 299.99} %}

{{ order|json_encode }}

Example Output Code