I was wondering if anyone knew if I can access JSON in Liquid such as the example below.
I have created a metafield for the suppliers page with the namespace suppliers_details
, with the key suppliers
and the value:
{
name: "Supplier Name One",
address: "Supplier Address One"
},
{
name: "Supplier Name Two",
address: "Supplier Address Two"
}
In the template I have:
{% assign suppliers = page.metafields.suppliers.suppliers %}
{% for supplier in suppliers %}
<p>{{ supplier.name }}</p>
<p>{{ supplier.address }}</p>
{% endfor %}
This doesn’t work as I can’t change the data into a format the the template can use to iterate through, is there a way to do this?
Cheers
4
Answers
There is no way to parse a JSON using Liquid or at least not a default way.
You can write some code to split it into parts, but you won’t be able to chain the objects:
You will get the wanted result, but not the same way you imagined it.
The best approach will be to pass the string to Javascript, parse it there and populate the DOM via JS.
This is now supported and is a game changer! Shopify released a new metafield format type called “json_string” that lets you directly access the value of each node via normal liquid dot notation. I know this will make EVERYONE’S life easier. Taken from the documentation (https://help.shopify.com/en/themes/liquid/objects/metafield):
Here was one of the initial posts from a Shopify developer on the Shopify forums that may help: https://ecommerce.shopify.com/c/api-announcements/t/new-json_string-value-type-for-metafield-object-540896
I think it is working now, below is my json , it is product metafield & valueType is json string
Blow is liquid code
Shopify has since deprecated the "json_string" metafield and supplied a "json" metafield option.
To access the data using dot notation, you need to use .value after the key.
For example, if I have this JSON:
I would access it like this: