I actually managed to get a capture (string) into a JS-parsable state.
{%- capture ecommerce_item -%}
{
"currency": "{{ currency.name }}",
"value": "{{ product.price }}",
"items": [ {
"item_id": "SKU_{{ product.variants[0].sku }}",
"item_name": "{{ product.variants[0].title }}",
"item_list_id": "list_name_example",
"item_list_name": "List name example",
"item_brand": "{{ product.vendor }}",
"currency": "{{ currency.name }}",
"location_id": "abc123def456",
"quantity": 1,
"index": 0,
"affiliation": "{{ shop.name }}",
{%- for collection in product.collections -%}
"item_category{% if forloop.first != true %}{{ forloop.index }}{% endif %}": "{{ collection.handle }}",
{%- endfor -%}
"price": "{{ product.price }}"
} ]
}
{%- endcapture %}
Later, you can render it in your HTML. Example:
<div id="example" data-ecommerce='{{- ecommerce_item | strip_newlines | strip_html | json -}}'>
It then can be fetched in JS:
JSON.parse( document.getElementById( 'example' ).dataset.ecommerce );
Note that the HTML itself in the page source will be converted, so you will find "e
tags. They do not prevent you from parsing it and using it in as JavaScript object.
I understand that this does not fully answer the question, but as it's related, I am leaving it here for later readers.