How to parse/decode JSON object in smarty template?

cookie669 picture cookie669 · Aug 4, 2013 · Viewed 19.9k times · Source

I have the following code in my template file:

{foreach from=$items item=entry}
  <pre>
    {$entry->nb_persons|@print_r}
  </pre>
{/foreach}

The output is (json string):

{"ip":"12.12.12.12","date":1375616434,"cartitems":["foo:1"],"company":"dsad","FirstName":"sad","LastName":"asdsad","street":"","postcode":"","city":"","country":"Andorra","phone":"456456","fax":"","email":"[email protected]","comefrom":"google","request":"","message":"sadads"}

I would like to print each element seperated, for example :

{$entry->nb_persons.company}

Should give me -> "dsad"

But this is not working and I'm not sure why.

Answer

dev-null-dweller picture dev-null-dweller · Aug 4, 2013

JSON string is just string. To access its members you have to create array/object from this string:

{foreach from=$items item=entry}
  {* create array from JSON string*}
  {assign var=person value=$entry->nb_persons|json_decode:1}
  <pre>
    {$person.company}
  </pre>
{/foreach}