Trying to figure out json_string metafields

New Member
10 0 0

I'm trying to figure out how the metafields work within a liquid theme. I set a json_string metafield with product materials and colors similar to:

{"linen":["black","white","red"],"leather":["black","white","red","natural"]}

But I'm trying to figure out a way I can iterate through either the associative keys (linen,leather) or the sub values. I have figured the latter out if I know or otherwise assume to know the keys. But I would like to collect the key information also.

When I tried doing a {% for material in product.metafields.global.materialcolors %} then I try to use material, it's not just the key but a squished string of the key and all associated values. e.g. linenblackwhitered

doing a console dump in javascript with the | json filter shows the datastructure is intact.

Am I missing something?

0 Likes
Shopify Partner
14 0 1

I don't believe liquid supports looping through the associative keys.  I recommend changing the json structure so that you can loop through an array instead.  If you need a list of keys then save that in the json_string as well:

{
   "keys":[
      "material",
      "colors"
   ],
   "options":[
      {
         "material":"linen",
         "colors":[
            "black",
            "white",
            "red"
         ]
      },
      {
         "material":"leather",
         "colors":[
            "black",
            "white",
            "red",
            "natural"
         ]
      }
   ]
}

 

0 Likes
New Member
10 0 0

@Brian_McKinley wrote:

I don't believe liquid supports looping through the associative keys.  I recommend changing the json structure so that you can loop through an array instead.  If you need a list of keys then save that in the json_string as well


Damn, I was afraid of that. But that kind of a solution means you have to step through the array of arrays to find what's in it. i.e. you can't reference an item by a known key. Does it use numeric indexing at least and does that indexing ever unpredictably shuffle? i.e. if I create an array of arrays and an array of keys in the same order, can I get the index of a key on the keys array to figure out what index of arrays corresponds to it?

0 Likes
Highlighted
Shopify Partner
14 0 1

Numeric indexing works and I have not seen any shuffle, but I have only experimented with the json type metafield  in liquid a couple of times.

0 Likes