parse a string into tokens in Shopify Liquid

liquid, parsing, shopify, tokenize

Solution

Liquid is pretty limited when it comes to creating arrays. The common approach is to use the `split` string filter.

In your case, it would look something like this:

{% assign my_str = 'a:3,b:1,c:2,d:2,e:2,f:2' %}
{% assign my_arr = my_str | split: ',' %}

{% for pair_str in my_arr %}
  {% assign pair_arr = pair_str | split: ':' %}
  ID: {{ pair_arr[0] }} Qty: {{ pair_arr[1] }} <br />
{% endfor %}

This blog post is also an interesting read on the topic of Liquid arrays: Advanced Arrays in Shopify's Liquid

Problem

I have the following string ("my_str") in a Shopify metafield: ``` a:3,b:1,c:2,d:2,e:2,f:2 ``` The keys are product variant IDs (shortened to a, b, c...) and the numbers are quantities. I need to parse it into key:value pairs so I can do something like this with it: ``` {% assign my_str = collection.metafields.local.my_metafield %} {% assign my_map = my_str | parse ???? %} {% for product in collection.products %} {% assign temp_qty = 1 %} {% for pair in my_map %} {% if pair[0] == product.variants.first.id %} {% assign temp_qty = pair[1] %} {% endif %} {% endfor %} <input type="hidden" id="abc-{{ forloop.index0 }}" value=temp_qty /> {% endfor %} ``` I definitely don't know how to parse my_str. I'm also open to suggestions about the best approach overall.

Original source