javascriptshopifyliquid

How to correctly display JSON array values from ACF metafields in a Shopify Liquid template?


I'm using the ACF plugin on my test site (which I use for website development) to add the ability to select clothing sizes for products. However, I'm currently unable to display this data, even though I'm following the documentation. Could you suggest what might be wrong?

Theme: Dawn 13.0.1 File: main-product.liquid

    <h2>ACF 'oval' Metafield Debug</h2>
    <p><strong>Raw JSON Value:</strong> {{ product.metafields.custom.oval }}</p>
    {% assign oval_array = product.metafields.custom.oval | parse_json %}
    <p><strong>Parsed Array:</strong> {{ oval_array | join: ', ' }}</p>

    <h3>Iterating Over 'oval' Array</h3>
    {% if oval_array.size > 0 %}
    <ul>
    {% for item in oval_array %}
    <li>{{ item }}</li>
    {% endfor %}
    </ul>
    {% else %}
    <p>Error: JSON is not parsed correctly.</p>
    {% endif %}

    {% if product.metafields.custom.oval %}
    <ul>
    {% for item in product.metafields.custom.oval %}
    <li>{{ item }}</li>
    {% endfor %}
    </ul>
    {% else %}
    <p>No items found in 'oval'.</p>
    {% endif %}

    Result:

    <h2>ACF 'oval' Metafield Debug</h2>
    <p><strong>Raw JSON Value:</strong> "["1","2","3"]"</p>
    <p><strong>Parsed Array:</strong> "["1","2","3"]"</p>
    <h3>Iterating Over 'oval' Array</h3>
    <p>Error: JSON is not parsed correctly.</p>
    <ul></ul>

[Result](https://i.sstatic.net/CiQRu.png)
[Settings](https://i.sstatic.net/kEZLM.png)
[Settings](https://i.sstatic.net/OBrpg.png)
[Settings](https://i.sstatic.net/WeGDq.png)

Solution

  • It seems like the issue lies in the format of the JSON string you're receiving from the metafield.

    Direct Output: Instead of using Liquid's {{ product.metafields.custom.oval }} to output the value, try directly outputting the value without Liquid interpreting it. For example:

    <p><strong>Raw JSON Value:</strong> {{ product.metafields.custom.oval | json }}</p>
    

    Custom Parsing: If the direct output doesn't work, you might need to manually parse the JSON string to remove the extra quotes. Here's how you can do it:

    {% assign oval_json = product.metafields.custom.oval %}
    {% assign oval_array = oval_json | replace: '"', '' | parse_json %}