Search code examples
jsonliquiddotliquid

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. Disclaimer: I am using the Shopify Liquid Preview extension for VSCode.

Input json file:

The input file contains two properties: CustomerId and Transactions, which is the 'dictionary' property, containing a list of KeyValuePairs. I want to loop through the Transactions collection and output the TransactionValue properties.

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

Expected 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]

<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.

Thank you


Solution

  • In most Liquid flavors it should be possible to reference an object field by name like this:

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

    Then it is a matter of getting all known transactionIds from somewhere. If they're not available as an array, then the dirty solution could be to parse raw incoming JSON, e.g. like that:

    {% 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>