【问题标题】:json_decode a nested array/objectjson_decode 嵌套数组/对象
【发布时间】:2022-01-18 01:02:17
【问题描述】:

我已收到此格式的订单/放弃购物车的 JSON 有效负载。

{
    "tokens": {
        "locale": "en_GB",
        "currency": "EUR",
        "entity_id": "36140",
        "item[0].type": "straw",
        "item[0].row_total_incl_tax": "2000.0000",
        "item[0].quantity": "2.0000",
        "item[0].name": "Diego",
        "item[0].straw_type": "itri",
        "item[0].mot": "20",
        "item[1].type": "virtual",
        "item[1].row_total_incl_tax": "625.0000",
        "item[1].quantity": "1.0000",
        "item[1].name": "Mixmatch",
        "item[2].type": "straw",
        "item[2].row_total_incl_tax": "1000.0000",
        "item[2].quantity": "1.0000",
        "item[2].name": "Diego",
        "item[2].straw_type": "abc",
        "item[2].mot": "20",
        "item[3].type": "straw",
        "item[3].row_total_incl_tax": "600.0000",
        "item[3].quantity": "1.0000",
        "item[3].name": "Pete",
        "item[3].straw_type": "itri",
        "item[3].mot": "20"
}
}

我可以打印 tokens.entity_id 之类的值 - 这很成功。 但是,对于每个项目,例如item[0] 我想使用 Twig 提取 item.name 以进行打印,但似乎无法完成这项工作。

我已经尝试了几件事,例如

{% set cart = contact.json_field | json_decode %}
{% for tokens in cart %}
Entity  : {{tokens.entity_id | raw }} <br>


{% for item in tokens %}
Item Name : {{item.name | raw }} <br>
{% endfor %}

{% endfor %}

我也尝试过 tokens.item.name、tokens.item1.name 和 tokens.item[1].name,但似乎永远无法提取项目的值。

如果我是 Twig 新手,我将不胜感激任何帮助

【问题讨论】:

    标签: json twig


    【解决方案1】:

    通过重组 json 数据设法解决了这个问题

    <ul>
     
    Item Name : {{tokens.entity_id | raw }}
    {% set count = 0 %}
    {% for item in tokens.items %}
    
    
    {% set counter = ( counter | default(0) ) + 1 %}
    {% set test = tokens.items.1.type %}
    {{counter}}
    
    Item Name : {{tokens.items.1.type | raw }}
    Item Name : {{tokens.items.1.row_total_incl_tax | raw }}
    {% endfor %} 
    </ul>
    

    json

            "link_order_status": "http://testing.com/en/",
            "items": {
                "0": {
                    "type": "straw",
                    "row_total_incl_tax": "400.0000"
                },
                "1": {
                    "type": "testing #1",
                    "row_total_incl_tax": "300.0000"
                },
                "2": {
                    "type": "testing #2",
                    "row_total_incl_tax": "200.0000"
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2020-03-11
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多