Add template filters to convert objects to and from JSON strings (#27909)

* Added filters to convert objects to and from JSON strings.

* Added extra spacing.

* Removed try/catch to get native exceptions

* Added tests.
This commit is contained in:
SteveDinn authored and Paulus Schoutsen committed 2019-10-22 22:51:29 -07:00
1 parent ab22c61764
commit 25fd930d67
2 files changed
+36

No files matched your search

+12
View File
@@ -884,6 +884,16 @@ def ordinal(value):
)
def from_json(value):
"""Convert a JSON string to an object."""
return json.loads(value)
def to_json(value):
"""Convert an object to a JSON string."""
return json.dumps(value)
@contextfilter
def random_every_time(context, values):
"""Choose a random value.
@@ -916,6 +926,8 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
self.filters["timestamp_custom"] = timestamp_custom
self.filters["timestamp_local"] = timestamp_local
self.filters["timestamp_utc"] = timestamp_utc
self.filters["to_json"] = to_json
self.filters["from_json"] = from_json
self.filters["is_defined"] = fail_when_undefined
self.filters["max"] = max
self.filters["min"] = min