user2758296
user2758296

Reputation: 59

Mule how to map Json values from payload to flow variables

I have a JDBC COnnector which retrieves values from the database and I have mapped them from object to JSON. Now I want to extract specific values from the json to flow variables. When I try to log #[message.payload], I get the full payload in the log which is in JSON format. However when I try to choose an attribute (eg. testattribute in json) #[message.payload.testattribute], I get mule expression error. How do I refer to the json values?

Upvotes: 4

Views: 15386

Answers (4)

muralidhar gumma
muralidhar gumma

Reputation: 87

If your requirement is to get the values from json data you can use a simple MEL expression like

#[json:<name of the node>] 

For example if you have an sample json data like this

{
"token" : 123,
"id" : 456,
"email" : "[email protected]",
"status" : "Success"
}

and if you want get the id from the data just use the below simple MEL.

#[json:'id']

Upvotes: 3

Jeevanantham
Jeevanantham

Reputation: 1022

Use components as follow

  1. Object - String
  2. Object - JSON

then u can directly extract using value using json expression as #{json:email}, in below xml i have used the variable component to set the #{json:email} in "var1" flow variable for usability

Note: json expression is even available in studio version of 5.x

 <object-to-string-transformer doc:name="Object to String"/>
 <json:object-to-json-transformer doc:name="Object to JSON"/>
 <set-variable variableName="var1" value="#[json:email]" doc:name="Variable"/>

Upvotes: 1

Anirban Sen Chowdhary
Anirban Sen Chowdhary

Reputation: 8311

Mule has JSON-to-Object transformer which can be used to get JSON elements. For example if your JSON is following :-

{
  "token" : 123,
  "id" : 456,
  "email" : "[email protected]",
  "status" : "Success"
}

Now, to extract the elements, you need to use :-

<json:json-to-object-transformer returnClass="java.lang.Object" doc:name="JSON to Object" />

And then can extract like :- #[message.payload.email] or #[message.payload.status]

Upvotes: 2

David Dossot
David Dossot

Reputation: 33413

Once the payload is a JSON string, you can't extract anything from it anymore with an expression.

So either:

  • use MEL to extract the values into flow variables prior to convert the payload into JSON,
  • transform the JSON payload to either POJOs or Map/Lists, use MEL to extract the values into flow variables, and re-transform the payload back to JSON.

Upvotes: 3

Related Questions