How to check if a key element exists and if present update it?

Aditya picture Aditya · Jul 24, 2017 · Viewed 7.8k times · Source

I am using mule community edition. So no Dataweave. I am consuming a rest service in my application. In the json response from this backend rest service. I need to check if a particular element exists inside muliple multiple elements of an array and wherever it exists I need to update its value.

E.g. (sample)

Input Request : [ { "id" : "1", "item" : "car", "make" : "Tonda" }, { "id" : "1", "item" : "car" } ]

using foreach to iterate array . Inside for each need to do something like below in expression component.

if( payload.make exists) { payload.make = "Tero"; }

But I do not know , how to check "if element exists"" condition. I tried below in expression component

if( payload.make != empty) { payload.make = "Tero"; }

But it did not work and gives error "Execution of the expression failed (org.mule.api.expression.ExpressionRuntimeException)"" for each array element wherever the particular key(make) is not present

Answer

Anirban Sen Chowdhary picture Anirban Sen Chowdhary · Jul 24, 2017

inside foreach use the expression: #[payload.containsKey('make')] to check if the json key make exists or not. This will return true or false

Easy and simple!
Ref: https://forums.mulesoft.com/questions/71478/how-to-check-if-a-key-element-exists-and-if-presen.html?childToView=71502#answer-71502