Search code examples
jsonmuleanypoint-studio

How to count elements in a JSON array


I want to get the count of faultInfoLst element from the below json array. I want to do an operation based on the count of that element. Help me to get count as I have to set it in session variable in mule flow.

[{"TaskInfo":
    {"faultInfo":
        {
            "errCode":"",
            "errDesc":"",
            "errSystem":""
        }
    }
},
{"TaskInfo":
    {"faultInfo":
        {
            "errCode":"",
            "errDesc":"",
            "errSystem":"",
            "errStack":""
        }
    }
}]

Solution

  • It seems that your goal can be achieved by simply getting the size of the array. It seems there's indeed a 1:1 relationship with faultInfo and TaskInfo.

    So based on: http://www.mulesoft.org/documentation/display/current/Mule+Expression+Language+Tips#MuleExpressionLanguageTips-JSONProcessing

    <json:json-to-object-transformer returnClass="java.lang.Object" />
    <set-variable variableName="faultInfoCount"
        value="#[($ in message.payload if $.TaskInfo.containsKey('faultInfo')).size()]" />