简体   繁体   中英

Joining array of objects using liquid template language

I'm building a liquid template to help convert some XML to JSON.

Sample XML input:

<ticket>
  <account-id type="integer">123456</account-id>
  <cc-email>
     <cc-emails type="array">
       <cc-email>abc@email.com</cc-email>
       <cc-email>xyz@email.com</cc-email>
     </cc-emails>
     <fwd-emails type="array">
       <fwd-email>abc@email.com</fwd-email>
       <fwd-email>xyz@email.com</fwd-email>
     </fwd-emails>
  </cc-email>
</ticket>

Desired JSON output:

{
  "account-id":"123456",
  "cc-email":"abc@email.com,xyz@email.com",
  "fwd-email":"abc@email.com,xyz@email.com"
}

Liquid template attempt 1:

{
    "account-id":"{{ ticket.account-id }}",

    {% assign list = '' | split: ',' %}
    {% for item in ticket.cc-email.cc-emails %}
        {% assign list = list | push: item %}
    {% endfor %}
    "cc-email":"{{ list | join: ',' }}",

    {% assign list = '' | split: ',' %}
    {% for item in ticket.cc-email.fwd-emails %}
        {% assign list = list | push: item %}
    {% endfor %}
    "fwd-email":"{{ list | join: ',' }}"
}

Liquid template attempt 2:

{
    "account-id":"{{ ticket.account-id }}",

    {% assign list = '' | split: ',' %}
    {% for item in ticket.cc-email.cc-emails %}
        {% assign list = list | push: item.cc-email %}
    {% endfor %}
    "cc-email":"{{ list | join: ',' }}",

    {% assign list = '' | split: ',' %}
    {% for item in ticket.cc-email.fwd-emails %}
        {% assign list = list | push: item.fwd-email %}
    {% endfor %}
    "fwd-email":"{{ list | join: ',' }}"
}

I've also tried appending the items to a string. No matter the method, I only get the following output:

{
  "account-id":"123456",
  "cc-email":"",
  "fwd-email":""
}

Can anyone help point out the issue? Seems like it has to be something simple but I haven't been able to find it.

Many thanks.

Ended up going back to appending strings. Got this to work:

    {% assign cc-email-list = '' %}
    {% for item in ticket.cc-email.cc-emails %}
       {% assign cc-email-list = cc-email-list | Append: item %}
       {% if forloop.last == false %}
          {% assign cc-email-list = cc-email-list | Append: ',' %}
       {% endif %}
    {% endfor %}
    "cc-email":"{{ cc-email-list }}",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM