Pablo Smith
Pablo Smith

Reputation: 23

Shopify Looping Over JSON Metafield Arrays

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

Upvotes: 1

Views: 3896

Answers (3)

Andi365
Andi365

Reputation: 3

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

Upvotes: 0

lov2code
lov2code

Reputation: 394

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!

Upvotes: 1

David Lazar
David Lazar

Reputation: 11427

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

Upvotes: 0

Related Questions