Matej Vrzala M4 Matej Vrzala M4 - 4 years ago 201
JSON Question

Twig loop through JSON

Array
(
[page_title] => Slovak RS
[page_footer] => © Copyright 2017
[is_published] => published
[menu] => {
"id":"1",
"name": "main_menu",
"items": [
"pos1": [
"display_name" : "Informácie",
"path" : "informacie"
],
"pos2": [
"display_name" : "Videá",
"path" : "video"
],
"pos4": [
"display_name" : "Recepty",
"path" : "recepty"
],
"pos5": [
"display_name" : "Galéria",
"path" : "galeria"
],
"pos6": [
"display_name" : "Osobnosti",
"path" : "osobnosti"
],
],
"updated_at": "2020"
}
)


This is data I'm getting into twig template file. I want to have menu in single db table stored as json. I can show items like
{{ menu }}, {{ page_title }}
, but have hard times looping through that json part

This is what i tried

{% for item in menu %}
{{ item.id }}
{{ item['id'] }}
{% endfor %}

{% for key,value in menu %}
Key : {{ key }}
Value : {{ value }}
{% endfor %}


I'm using twig 2.x and I'm newbie

Answer Source

You should json_decode the JSON first, before you're passing it to twig. With that, you have an array or object, that you can loop through.

$objJson = json_decode($yourDBArray['menu']);
$arrJson = json_decode($yourDBArray['menu'],true);

In the code you've provided, the JSON is a string and not an array nor an object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download