PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 1, 2022

[FIXED] How to access key name in json_string type of Shopify?

 July 01, 2022     liquid, shopify     No comments   

Issue

For example I have this JSON string in product_supplier['shipping_to']:

{"United States": {"time": "1-3"}, "Worldwide": {"time": "10-15"}}

How can I access the country name in liquid? Tried this:

{% for country, time in product_supplier['shipping_to'] %}
  {{ country }}: {{ time['time'] }}
{% endfor %}

Which obviously doesn't work as it gives error: Liquid syntax error: Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]

And tried this:

{% for country in product_supplier['shipping_to'] %}
  {{ country[0] }}, {{ country[1] }}
{% endfor %}

Which gives empty output with just a comma:

,

From the official doc here, it seems it's only able to access the values not keys?


Solution

If you saved the metafield as json_string then you can do this.

{% for item in product.metafields.product_supplier.shipping_to %}
 {{item[0]}}<br/>
{% endfor %}

The response will be:

United States
Worldwide

Once again this must be as json string to work.

So it similar to your third example but we are using the proper object (in this case product.metafields) to target that metafield.

Tested it on my end it works without a problem.



Answered By - drip
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing