How to use JSON data in Shopify liquid code

by Ilias Haddad

Welcome to the 11th article of the #4weeksOfShopifydev challenge! In this article, we will explore how to effectively utilize JSON data in Shopify Liquid code.

Shopify's Liquid template language does not inherently support JSON or objects (excluding product objects). However, there's a workaround to use JSON within Liquid.

Steps to Use JSON with Shopify Liquid:

  1. Install the Metafields Guru App:

    To create metafields, you need to install the Metafields Guru app.

  2. Create a New Metafield Under Shop Settings:

    After installing the Metafields Guru app, navigate to Shop settings and create a new metafield.

    • Select JSON String as Type:Choose JSON string as the type and set 'data' as the key.

Sample JSON Data:

Here is a sample JSON data structure:

[
  {
    "firstName": "Ilias",
    "lastName": "Haddad",
    "email": "contact@iliashaddad.com"
  }
]

Rendering JSON Data in Liquid:

To consume and display this JSON data in Liquid, you can use the following code snippet:

{% assign users = shop.metafields.global %}
{% for user in users.data  %}
  {{ user.firstName }}  {{ user.lastName }}  {{ user.email }}
{% endfor %}

In this snippet:

  • We assign the global namespace metafield to a variable named users
{% assign users = shop.metafields.global %}
  • We then loop over the array of objects in JSON by accessing the 'data' key of the metafield
{% for user in users.data  %}
  {{ user.firstName }}  {{ user.lastName }}  {{ user.email }}
{% endfor %}

By following these steps, you can effectively use JSON data in your Shopify Liquid code. This method allows you to extend the capabilities of Liquid and work with structured data more efficiently.

  • #4WeeksOfShopifyDev

Tell me about your project