简体   繁体   English

如何在 smarty 模板中解析/解码 JSON 对象?

[英]How to parse/decode JSON object in smarty template?

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):输出是(json字符串):

{"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":"sad@sad.com","comefrom":"google","request":"","message":"sadads"}

I would like to print each element seperated, for example :我想单独打印每个元素,例如:

{$entry->nb_persons.company}

Should give me -> "dsad"应该给我 -> "dsad"

But this is not working and I'm not sure why.但这不起作用,我不知道为什么。

JSON string is just string. JSON 字符串只是字符串。 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}

I'm not an expert with Smarty, but I think you're trying to access the property of a JSON structured string.我不是 Smarty 的专家,但我认为您正在尝试访问 JSON 结构化字符串的属性。
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!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM