skip to Main Content

For some reason, I can’t access an array within a JSON metafield.. I’ve tried the other StackOverflow answers, and I’m using value, etc. but just can’t figure it out, here’s my metafield:

product.metafields.artist.releases

with a value of:

{
  "releases": [
   { 
    "id": 0,
    "releaseName": "lofi 1",
    "coverArt": "",
    "releaseLink": “”
},
 { 
"id": 1,
    "releaseName": " lofi 2",
    "coverArt": "",
    "releaseLink": “”
  }
]}

(which formats to: "{"releases":[{"id":0,"releaseName":"lofi 1","coverArt":"","releaseLink":“”},{"id":1,"releaseName":"lofi 2","coverArt":"google.com","releaseLink":“”}]}")

and I’m using this in the product.custom.liquid:

{{ product.metafields.artist.releases.value }}
  
{% assign releases = product.metafields.artist.releases.value %}
  
  {% for release in releases.releases %}
  
    {{ release.releaseName }}
  
  {% endfor %}

the first one shows up fine, and if I assign it and do {{ releases }} it shows up fine as well so I know the assignment is working, but I can’t forloop over it (mind you that the first object in the JSON is also called releases (I’ve also tried renaming it all to unique names just in case and that didn’t help))

3

Answers


  1. Liquid is not going to work on JSON like this. If you want to iterate through an array of JSON objects, use Javascript.

    Login or Signup to reply.
  2. For some reason when it is a multidimensional JSON array it acts weird. There is a simple fix for it, just add (-) at the end of your assigned variable:

    {%- assign releases = product.metafields.artist.releases.value -%}
      
      {% for release in releases.releases %}
      
        {{ release.releaseName }}
      
      {%- endfor -%}
    

    Hope it solves your problem like it did mine!

    Login or Signup to reply.
  3. As lov2code points out by adding (-) it trims the output for any unnecessary white space, which enables you to traverse the JSON array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search