jsonazuretransformazure-logic-appsdotliquid

How to use foreach and append string in liquid json transformation


Original Input json -

{
 "demo" : "a12,b45,c78" ,
 "status" :  "1" 
}

Expected output is xml

<demo>
<Value>a12</Value>
<Value>b45</Value>
<Value>c78</Value>
</demo>
<status>done</status>

I will first create a json and then use @xml() in logic app to convert this into xml tried like below which works fine but its hardcoded how to use foreach for dynamic.

{
 {% if content.status == "1" %}
 "status" : "done"
 {% elsif content.status == "2" %} 
      "status" : "done"
 {% endif %}
"demo": {"Value":["a12","b45","c78"]}
}

for demo c# code will be like -

 string a = "a12,b45,c78";

            var aa = a.Split(',').ToArray(); 

Solution

  • For this requirement, we can use some actions in logic app to get "a12,b45,c78" and then split them to array, then convert them from json to xml. But I think this solution is too complicated, we may need to do many operations in logic app. So in your logic app, you can do what you have done before and get the result <demo>a12,b45,c78</demo>. Then use xslt map to transform ths xml to the format which you want. Please refer to the steps below:

    1. I do the same operation as you mentioned in your question. enter image description here

    2. We need to create a xslt template as below:

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="demo/text()" name="tokenize">
            <xsl:param name="separator" select="','"/>
            <xsl:for-each select="tokenize(.,$separator)">
                    <Value>
                        <xsl:value-of select="normalize-space(.)"/>
                    </Value>
            </xsl:for-each>
        </xsl:template>
    </xsl:stylesheet>
    

    3. Save the xslt template as the type of .xslt and upload it to the Map of your integration account. When you do the upload, please choose "Map type" as "XSLT 2.0".

    4. Use Transform XML action to do the transform (choose the map which you uploaded above). enter image description here

    5. After that, we can get the result which you want. enter image description here

    Update:

    You can use the liquid template as below:

    {% assign arr = content.demo | Split: "," %}
    {
        {% if content.status == "1" %}
            "status": "done",
        {% else %}
            "status": "undone",
        {% endif %}
        "demo": {
            "Value":[
                {% for item in arr  %}
                    "{{item}}",
                {% endfor %}
            ]
        }
    }
    

    Then get the json data which you want:

    {
      "status": "done",
      "demo": {
        "Value": [
          "a12",
          "b45",
          "c78"
        ]
      }
    }