How to parse/decode JSON object in smarty template?
Asked Answered
S

2

8

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.

Stricklin answered 4/8, 2013 at 12:23 Comment(2)
What do you mean by separated?Suzansuzann
Thanks Jhon' I meant print only the value as shoven above {$entry->nb_persons.company} -> "dsad". Thanks again...Stricklin
T
16

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}
Turnstile answered 4/8, 2013 at 12:45 Comment(1)
@Stricklin May I ask why have you changed accepted answer? If something is wrong with my version, let me know.Turnstile
A
3

I'm not an expert with Smarty, but I think you're trying to access the property of a JSON structured string.
Try to decode it first to an object and then access it.

Something like this:

{foreach $items as $entry}
  {assign var="person" value="{$entry->nb_persons|@json_decode}"}
  <pre>
    {$person.company}
  </pre>
{/foreach}

I didn't test it, though.

Good luck!

Aracelyaraceous answered 4/8, 2013 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.