shopify-json-parser icon indicating copy to clipboard operation
shopify-json-parser copied to clipboard

usage with complex json

Open jaymecd opened this issue 8 years ago • 1 comments

@evulse I get stuck with complex json struct. Could you pls adjust following liquid code with usage of shopify-json-parser?

{% assign json = product.metafields.my_ns.complex_json %}
{% unless json == empty %}
    <dl id="my-list" data-id="{{ json.ref_id }}">
        <dt>{{ json.title }} ({{ json.items.size }} items):<dt>
    {% for item in json.items %}
        <dd data-ref="{{ item.ref }}">
            "{{ item.title }}" has {{ item.points.size }} points:
            <ul>
            {% for point in item.points %}
                <li>{{ point.label }} - x:{{ point.x }} y:{{ point.y }}</li>
            {% endfor %}
            </ul>
        </dd>
    {% endfor %}
    </dl>
{% endunless %}

where product.metafields.my_ns.complex_json is:

{
  "ref": "ref-123",
  "title": "main title",
  "items": [
     {
        "ref": "item-1",
        "title": "item 1",
        "points": [
           {
              "label": "point-1",
              "x": 1.1,
              "y": 1.1
           },
           {
              "label": "point-2",
              "x": 1.2,
              "y": 1.2
           }
        ]
     }
  ]
}

Highly appreciated for support.

jaymecd avatar Jun 16 '17 10:06 jaymecd

I finally manage to make mine work. For your data I'd do something like


  {%- capture 'json' -%}
    {{product.metafields.my_ns.complex_json}}
  {%- endcapture -%}

  {%- capture json_error -%}
      {%- include 'json_decode' jd__namespace:'my_fields' jd__data:json -%}
  {%- endcapture -%}

  //now we get items keys to iterate
  {%- include 'jd__function' with 'keys|my_fields.items' -%}{%- assign items = jd__yield_1 -%}
  
  <dl>  
  {%- for key in items -%}

    // We get the value of each key and stored in item
    {%- include 'jd__function' with key -%}{%- assign item = jd__yield_1 -%}  

    // We concat the correct path/key to the value in item and store it in title_path
    {% capture title_path %}echo|{{ key }}.title{% endcapture %}
    {% capture ref_path %}echo|{{ key }}.ref{% endcapture %}

    // And we render
    <dd data-ref="{% include 'jd__function' with ref_path %}">
       <h1>{% include 'jd__function' with title_path %}</h1>
    </dd>

  {%- endfor -%}
  </dl> 

From there I think the nested points array should be a combination of the above. Probably changing the concatenation of keypath -- echo| to keys| -- to do the same nested process.

juanpasolano avatar Nov 11 '17 18:11 juanpasolano