[英]How to handle json dictionary in Liquid templates?
我對 Liquid 模板相當陌生,但我似乎沒有找到一種方法來遍歷 json 中的字典並訪問不同的值。 免責聲明:我正在使用 VSCode 的 Shopify Liquid Preview 擴展。
輸入 json 文件:
輸入文件包含兩個屬性: CustomerId
和Transactions
,它是“字典”屬性,包含 KeyValuePairs 列表。 我想遍歷 Transactions 集合和 output TransactionValue
屬性。
{
"CustomerId": 13,
"Transactions": {
"1": {
"Id": "1",
"TransactionValue": 1000
},
"2": {
"Id": "2",
"TransactionValue": 207.47
}
}
}
預期 output:
<h1>Customer 13</h1>
<ul>
<li>1000</li>
<li>207.47</li>
</ul>
當前嘗試
我可以輕松地循環集合,但是我不清楚如何訪問當前事務的實際屬性。 以下都不起作用。 當只是輸出變量時,它會像這樣打印: 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>
我真的無法控制輸入 json,所以我希望能找到一個好的方法來完成這項工作。
謝謝
在大多數 Liquid 風格中,應該可以通過如下名稱引用 object 字段:
{{ Transactions["1"].TransactionValue }}
然后是從某個地方獲取所有已知的 transactionIds 的問題。 如果它們不能作為數組使用,那么骯臟的解決方案可能是解析原始傳入的 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.