diff --git a/CHANGELOG-v3.md b/CHANGELOG-v3.md index 6f41f0ae7ea..57aef1d4d55 100644 --- a/CHANGELOG-v3.md +++ b/CHANGELOG-v3.md @@ -2,6 +2,9 @@ ## Unreleased +### Added +- Added the `|json_decode` Twig filter. ([#3678](https://github.com/craftcms/cms/pull/3678)) + ### Fixed - Fixed an error that occurred when updating to Craft 3.1 if a plugin or module was calling any soft-deletable records’ `find()` methods. - Fixed an error that occurred when updating from Craft 2 to Craft 3.1 if there were any RichText fields. ([#3677](https://github.com/craftcms/cms/issues/3677)) diff --git a/docs/dev/filters.md b/docs/dev/filters.md index db362d954df..55d306ca747 100644 --- a/docs/dev/filters.md +++ b/docs/dev/filters.md @@ -247,6 +247,14 @@ Returns an array containing only the values that are also in a passed-in array. Like Twig’s core [json_encode](https://twig.symfony.com/doc/2.x/filters/json_encode.html) filter, but if the `options` argument isn’t set, it will default to `JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT` if the response content type is either `text/html` or `application/xhtml+xml`. +## `json_decode` + +JSON-decodes a string into an array by passing it through . + +```twig +{% set arr = '[1, 2, 3]'|json_decode %} +``` + ## `kebab` Returns a string formatted in “kebab-case”. diff --git a/src/web/twig/Extension.php b/src/web/twig/Extension.php index 68647fd077e..ba5a134b8d5 100644 --- a/src/web/twig/Extension.php +++ b/src/web/twig/Extension.php @@ -16,6 +16,7 @@ use craft\helpers\DateTimeHelper; use craft\helpers\Db; use craft\helpers\FileHelper; +use craft\helpers\Json; use craft\helpers\Sequence; use craft\helpers\StringHelper; use craft\helpers\Template as TemplateHelper; @@ -213,6 +214,7 @@ public function getFilters(): array new \Twig_SimpleFilter('indexOf', [$this, 'indexOfFilter']), new \Twig_SimpleFilter('intersect', 'array_intersect'), new \Twig_SimpleFilter('json_encode', [$this, 'jsonEncodeFilter']), + new \Twig_SimpleFilter('json_decode', [Json::class, 'json_decode']), new \Twig_SimpleFilter('kebab', [$this, 'kebabFilter']), new \Twig_SimpleFilter('lcfirst', [$this, 'lcfirstFilter']), new \Twig_SimpleFilter('literal', [$this, 'literalFilter']),