Cleaner way to turn string separated by commas into JSON using Shopify Liquid?
I've got this working, but I was wondering if there is a cleaner way to write this using liquid. I'm pulling a string from theme settings which would like this:"keyOne: valueOne, keyTwo:ValueTwo, keyThree:ValueThree"
Then in my liquid file I have this: this is getting the string
{% assign messageList = settings.message | split: ',' %}
Loops over messageList and as long as there is a length it splits the text again by the colon and returns the key and value wrapped in quotes. Then checking the last iteration so that it doesn't add the comma
<script class="js-product-messages" type="application/json">
{
{%- for messages in messageList -%}
{%- if forloop.length > 0 -%}
{%- assign singalMessage = messages | split:':' -%}
"{{ singalMessage[0] | strip}}":"{{ singalMessage[1] | strip}}"{% unless forloop.last %},{% endunless -%}
{%- endif -%}
{%- endfor -%}
}
</script>
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.