简体   繁体   English

如何处理 Liquid 模板中的 json 字典?

[英]How to handle json dictionary in Liquid templates?

I am rather new to Liquid templates, but I don't seem to find a way to loop through a dictionary in json and access the different values.我对 Liquid 模板相当陌生,但我似乎没有找到一种方法来遍历 json 中的字典并访问不同的值。 Disclaimer: I am using the Shopify Liquid Preview extension for VSCode.免责声明:我正在使用 VSCode 的 Shopify Liquid Preview 扩展。

Input json file:输入 json 文件:

The input file contains two properties: CustomerId and Transactions , which is the 'dictionary' property, containing a list of KeyValuePairs.输入文件包含两个属性: CustomerIdTransactions ,它是“字典”属性,包含 KeyValuePairs 列表。 I want to loop through the Transactions collection and output the TransactionValue properties.我想遍历 Transactions 集合和 output TransactionValue属性。

{
    "CustomerId": 13,
    "Transactions": {
        "1": {
            "Id": "1",
            "TransactionValue": 1000
        },
        "2": {
            "Id": "2",
            "TransactionValue": 207.47
        }
    }
}

Expected output:预期 output:

<h1>Customer 13</h1>
<ul>
    <li>1000</li>
    <li>207.47</li>
</ul>

Current Attempt当前尝试

I can easily loop the collection, but then it's not clear to me on how I can access the actual properties of the current transaction.我可以轻松地循环集合,但是我不清楚如何访问当前事务的实际属性。 None of the following work.以下都不起作用。 When just outputting the variable, it gets printed like this: 1,[object Object]当只是输出变量时,它会像这样打印: 1,[object Object]

<ul>
{% for trx in Transactions %}
    <li>{{trx}}</li>
    <li>{{trx.Key}}</li>
    <li>{{trx.Value}}</li>
    <li>{{trx.Object}}</li>
{% endfor %}
</ul>

I don't really have control over the input json, so I was hoping to find a good way on making this work as is.我真的无法控制输入 json,所以我希望能找到一个好的方法来完成这项工作。

Thank you谢谢

In most Liquid flavors it should be possible to reference an object field by name like this:在大多数 Liquid 风格中,应该可以通过如下名称引用 object 字段:

{{ Transactions["1"].TransactionValue }}

Then it is a matter of getting all known transactionIds from somewhere.然后是从某个地方获取所有已知的 transactionIds 的问题。 If they're not available as an array, then the dirty solution could be to parse raw incoming JSON, eg like that:如果它们不能作为数组使用,那么肮脏的解决方案可能是解析原始传入的 JSON,例如:

{% assign transactionIds = Transactions | split: "\"Id\": \"" %}
<ul>
{% for id in transactionIds %}
    {% if id[0] != "{" %}
        {% assign realId = id | split: "\"" | first %}
        <li>
            {{ Transactions[realId].TransactionValue }}
        </li>
    {% endif %}
{% endfor %}
</ul>

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

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