'How to translate a JSON string into a usable object [duplicate]
I´ve the following presets in my db stored as LONGTEXT:
[
{
"timewindow": "21:00-24:00",
"mas": "2"
},
{
"timewindow": "00:00-02:00",
"mas": "2"
},
{
"timewindow": "02:00-04:00",
"mas": "2"
}
]
I pass this JSON String to my TWIG3-Template and try to iterate over it, like this:
{% set presets = service.preset|json_encode|raw %}
{% for preset in presets %}
<tr id="{{service.shortname}}_shift_{{loop.index}}">
<td><input type="text" name="{{service.shortname}}_timewindow_{{loop.index}}" value="{{preset.timewindow}}" required></td>
<td><input type="number" name="{{service.shortname}}_amountma_{{loop.index}}" value="{{preset.mas}}" required></td>
</tr>
<input type="hidden" name="{{service.shortname}}_id_{{loop.index}}" value="{{service.id}}" required>
{% endfor %}
Unfortunately there is no output. When I display the variable {{presets}} it shows an escaped view of the JSON like this:
[{\"timewindow\": \"21:00-24:00\", \"mas\": \"2\"},{\"timewindow\": \"00:00-02:00\", \"mas\": \"2\"},{\"timewindow\": \"02:00-04:00\", \"mas\": \"2\"}]
Maybe there is the problem? So my question is, how can I translate a JSON string into a usable TWIG object.
Solution 1:[1]
Thx DarkBee, I knew that article you mentioned, but I thought I couldn“t use it, as I use TWIG standalone. This is how I solved my problem:
I added the marked line to my index.php:
$app = AppFactory::create();
$twig = Twig::create('../application/view/', ['cache' => false]);
// add start
$twig->addExtension(new Application\TwigExtension);
// add end
$app->add(TwigMiddleware::create($app, $twig));
And at least I put a TwigExtension.php in my core model:
<?php
namespace Application;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class TwigExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('jsonDecode', [$this, 'jsonDecode']),
];
}
public function jsonDecode($string)
{
return json_decode($string);
}
}
Now I can use this line for decoding JSON:
{% set presets = jsonDecode(service.preset) %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | meDom |
