diff --git a/source/_docs/configuration/templating.markdown b/source/_docs/configuration/templating.markdown index 2e48f0bf1a0..14bd0c1420c 100644 --- a/source/_docs/configuration/templating.markdown +++ b/source/_docs/configuration/templating.markdown @@ -655,13 +655,14 @@ To fix it, enforce the ISO conversion via `isoformat()`: The `to_json` filter serializes an object to a JSON string. In some cases, it may be necessary to format a JSON string for use with a webhook, as a parameter for command-line utilities or any number of other applications. This can be complicated in a template, especially when dealing with escaping special characters. Using the `to_json` filter, this is handled automatically. -Similarly to the Python equivalent, the filter accepts an `ensure_ascii` parameter, defaulting to `True`. If `ensure_ascii` is `True`, the output is guaranteed to have all incoming non-ASCII characters escaped. If `ensure_ascii` is false, these characters will be output as-is. +`to_json` also accepts boolean arguments for `pretty_print`, which will pretty print the JSON with a 2-space indent to make it more human-readable, and `sort_keys`, which will sort the keys of the JSON object, ensuring that the resulting string is consistent for the same input. + +If you need to generate JSON that will be used by a parser that lacks support for Unicode characters, you can add `ensure_ascii=True` to have `to_json` generate Unicode escape sequences in strings. The `from_json` filter operates similarly, but in the other direction, de-serializing a JSON string back into an object. -### To/From JSON examples -In this example, the special character '°' will be automatically escaped in order to produce valid JSON. The difference between the stringified object and the actual JSON is evident. +### To/From JSON examples #### Template @@ -670,7 +671,7 @@ In this example, the special character '°' will be automatically escaped in ord ```text {% set temp = {'temperature': 25, 'unit': '°C'} %} stringified object: {{ temp }} -object|to_json: {{ temp|to_json(ensure_ascii=False) }} +object|to_json: {{ temp|to_json(sort_keys=True) }} ``` {% endraw %} @@ -681,7 +682,7 @@ object|to_json: {{ temp|to_json(ensure_ascii=False) }} ```text stringified object: {'temperature': 25, 'unit': '°C'} -object|to_json: {"temperature": 25, "unit": "\u00b0C"} +object|to_json: {"temperature": 25, "unit": "°C"} ``` {% endraw %} @@ -693,7 +694,7 @@ Conversely, `from_json` can be used to de-serialize a JSON string back into an o {% raw %} ```text -{% set temp = '{"temperature": 25, "unit": "\u00b0C"}'|from_json %} +{% set temp = '{"temperature": 25, "unit": "°C"}'|from_json %} The temperature is {{ temp.temperature }}{{ temp.unit }} ```