Metaobject field being returned as a string instead of an array

I have a metaobject that has a field called color of type color that is a list of values. In liquid the output of this field looks to be an array but .size was always returning null and following code would not work.

{%- assign swatch = shop.metaobjects.material_colors[material_value_downcase] -%}
{%- if swatch.color.size == 1 -%}

When I output the value of {{ swatch.color }}, it displays

["#00000","#3d7fa1"]

I have solved my problem by replacing text and splitting the string to make an array, but this seems like a hack as I would expect the list of items to be returned as an array in the first place. Should this be reported as a bug?

{% assign colors = swatch.color | replace: ' ', '' | replace: '[', '' | replace: ']', '' | replace: '"', '' | split: ',' %}

Hi @s40er ,

The output of this is an array.

{%- assign swatch = shop.metaobjects.material_colors[material_value_downcase] -%}

To call the elements inside the array, you need a forloop. The {{ color }} will return a string

{%- assign swatch = shop.metaobjects.material_colors[material_value_downcase] -%}
{% for color in swatch %}
{{ color }}
{% endfor %}

Regarding the size, you are asking a size to a variable that is not an array. If you want to use the size of color in your metaobjects, please use the code instead

{% if swatch.size == 1 %}
Your code here
{% endif %}

@made4Uo , Thanks for the quick reply, but I tested and confirmed your solution is not valid as swatch is not an array and is the metaobject with the following properties. Name - single line text, and color which is a list of values.

{%- assign swatch = shop.metaobjects.material_colors[material_value_downcase] -%}

i.e. swatch = { name: "Black and Green",  color: ["#00000", "#3C9C3C"] }

the value of swatch.color when displayed to the screen looks like a valid array in any other coding language, but is not working as an array in Liquid and is just text and that’s my issue.

I have finally solved this issue with out the need to use split. When retrieving data from a field that is a list of values, you need to add .value to the end.

I have a metaobjects called swatch_colors that has a field color that is a list of values.

When I tried to get the array of colors with this code:

{%- assign swatch = shop.metaobjects.swatch_colors[color_value_downcase] -%}
{%- assign colors = swatch.color -%}
{%- if colors.size < 1 -%}

‘colors’ would equal a string that looked like:

["#00000","#3d7fa1"]

and ‘colors.size’ would just return null

The solution is to retrieve it with .value then colors is a proper array and .size works.

{%- assign swatch = shop.metaobjects.swatch_colors[color_value_downcase] -%}
{%- assign colors = swatch.color.value -%}
{%- if colors.size < 1 -%}