Search code examples
wso2-api-managerwso2wso2-enterprise-integratorwso2-esb

WSO2 Loop through Json array


This is my input Json :

How to get "Value" fields and set it to property?

 [
        {
            "Name": "dasdsadasd",
            "Value": "99999",
            "ParameterName": "{param01}",
            "IsRequired": "1",
            "MinLength": "5",
            "MaxLength": "10",
            "Type": "String"
        },
        {
            "Name": "dans",
            "Value": "99115544",
            "ParameterName": "{}",
            "IsRequired": "1",
            "MinLength": "5",
            "MaxLength": "10",
            "Type": "String"
        },
        {
            "Name": "dfd",
            "Value": "88554455",
            "ParameterName": "{}",
            "IsRequired": "1",
            "MinLength": "5",
            "MaxLength": "10",
            "Type": "String"
        }
    ]

When i loop through json, i can only get last iteration

Desired Output :

{
"val1" : "95252351",
"val2" : "99115544",
"val3" : "88554455"
}

Solution

  • Generating field names for a JSON object is not possible. You can get an output like below by using the given proxy.

    output JSON

    {
        "values": [
            95252351,
            99115544,
            88554455
        ]
    }
    

    proxy service

    <?xml version="1.0" encoding="UTF-8"?>
    <proxy name="test2" startOnLoad="true" transports="http https" xmlns="http://ws.apache.org/ns/synapse">
        <target>
            <inSequence>
                <log level="full">
                    <property name="log1" value="invoked"/>
                </log>
                <property name="messageType" scope="axis2" type="STRING" value="application/xml"/>
                <property name="Content-Type" scope="transport" type="STRING" value="application/xml"/>
                <log level="full">
                    <property name="log2" value="after conversion"/>
                </log>
                <foreach expression="//jsonArray/jsonElement" id="foreach">
                    <sequence>
                        <payloadFactory media-type="xml">
                            <format>
                                <values xmlns="">$1</values>
                            </format>
                            <args>
                                <arg evaluator="xml" expression="//jsonElement/Value" literal="true"/>
                            </args>
                        </payloadFactory>
                    </sequence>
                </foreach>
                <property name="messageType" scope="axis2" type="STRING" value="application/json"/>
                <property name="Content-Type" scope="transport" type="STRING" value="application/json"/>
                <respond/>
            </inSequence>
            <outSequence/>
            <faultSequence/>
        </target>
    </proxy>