Add documentation for to_json options (#26956)

Co-authored-by: Franck Nijhof <frenck@frenck.nl>
This commit is contained in:
David Poll 2023-04-12 17:35:04 -05:00 committed by GitHub
parent c30ec90dde
commit 1303de1a87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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 }}
```