"Enhancing JSON elements on the fly with WSO2's enrich mediator: A step-by-step guide

I attempted to utilize the following configuration:

 <property name="messageType" scope="axis2" type="STRING" value="application/xml"/>
    <property expression="get-property('orderSourceSF')" name="orderSource" scope="default" type="STRING"/>
    <enrich description="">
        <source type="property"  property="orderSource"></source>
        <target action="child" xpath="$body//jsonObject"/>
    </enrich>
    <property name="messageType" scope="axis2" type="STRING" value="application/json"/>
    <payloadFactory media-type="json">
           <format>{request : $1}</format>
           <args>
               <arg evaluator="xml" expression="$body//jsonObject"/>
           </args>
       </payloadFactory>

My goal is to insert an element called orderSource into the existing JSON payload. How do I go about accomplishing this task? I have managed to capture the value of orderSource, but am struggling with inserting the element along with its value.

Answer №1

I have created a mediation example that can be used to address your specific use case.

    <?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="enrichProxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <property expression="json-eval($)"
                   name="orderSource"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="json-eval($)" name="orderSource"/>
         </log>
         <call>
            <endpoint>
               <address uri="http://run.mocky.io/v3/9cf4b844-57c1-4fa5-a101-881dc36385bd"/>
            </endpoint>
         </call>
         <log level="full"/>
         <property name="messageType"
                   scope="axis2"
                   type="STRING"
                   value="application/json"/>
         <enrich>
            <source clone="false" property="orderSource" type="property"/>
            <target action="child" xpath="json-eval($)"/>
         </enrich>
         <payloadFactory media-type="json">
            <format>{"request" : $1}</format>
            <args>
               <arg evaluator="json" expression="$"/>
            </args>
         </payloadFactory>
         <respond/>
      </inSequence>
   </target>
   <description/>
</proxy>
                            

I have chosen to use JSON paths instead of XPATH for better performance in handling JSON payloads during mediation.

The proxy service is invoked with the payload:

{"orderSource":"value"}

We capture this payload using JSON path and store the value in the property mediator orderSource. Then we make an endpoint call which returns the JSON payload:

{"first":"response"}

To incorporate the value of the property mediator into the second payload, we utilize the enrich mediator to achieve the following payload:

{
        "first": "response",
        "orderSource": "value"
 }

To further manipulate the generated payload as a value in another JSON element, a payload factory mediator is used. This results in the following payload after the mediation:

{
    "request": {
        "first": "response",
        "orderSource": "value"
    }
}

For more information on JSON Support in WSO2, refer to [1].

Updated

The mediation has been modified to use XPATH functions instead of JSON path. Please refer to the sample configuration below:

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="enrichProxy2"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <property name="messageType"
                   scope="axis2"
                   type="STRING"
                   value="application/xml"/>
         <enrich>
            <source clone="true" xpath="$body//jsonObject/*"/>
            <target property="orderSource" type="property"/>
         </enrich>
         <call>
            <endpoint>
               <address uri="http://run.mocky.io/v3/9cf4b844-57c1-4fa5-a101-881dc36385bd"/>
            </endpoint>
         </call>
         <enrich>
            <source clone="false" property="orderSource" type="property"/>
            <target action="child" xpath="//jsonObject"/>
         </enrich>
         <enrich>
            <source clone="true" xpath="//jsonObject"/>
            <target type="body"/>
         </enrich>
         <respond/>
      </inSequence>
   </target>
   <description/>
</proxy>
           

Update 2

To disable automatic data conversion, you can set synapse.commons.json.output.autoPrimitive = false in the synapse.properties file [2].

For more details, refer to the link [2] for insights on JSON handling in WSO2 ESB.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The div has extra white space at the bottom due to the Hide/Show content feature

Having trouble stretching a scrolling div to 100% of its parent container's height? The Hide/Show content feature is causing whitespace at the bottom of the div. Check out the jsfiddle here: http://jsfiddle.net/fkvftff2/1/ LATEST UPDATE: The issue a ...

What is the process for displaying a String Value on the iPhone 6.0 Simulator after receiving JSON data?

Received the following data from my server: 2014-06-04 13:58:40.201 myRequest[2349:11303] parsing JSON: { "is_vip" = 1; "my_balance" = "1000.21"; "my_name" = "my_foo"; "my_num" = 100; } All values are being printed correctly. However, ...

Update specific fields in a MySQL database using Express.js only if they are passed as parameters

After spending several days trying to set up a REST API, I found a helpful tutorial that explained the basics of sending requests and receiving responses. The only issue is that the tutorial uses MongoDB and Mongoose, while I'm working with MySQL. Due ...

How to grab JSON data within a CakePHP 2.2 controller

Trying to transmit JSON data from a web page using JQuery, as shown below: $.ajax({ type: "post", url: "http://localhost/ajax/login", data: '{username: "wiiNinja", password: "isAnub"}', dataType: "json", contentType: "applica ...

Tips for effectively utilizing node modules that have yet to be installed without encountering any errors

I am looking to create a setup script for my NodeJS application. The script will: Establish system roles for users Create a root category for posts Finally, create a system admin user for the initial login These details will be saved in a database. Ad ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Verifying the type and quantity of an item

Looking at a piece of code where a specific condition is being checked, I'm curious to know why someone might want to skip this particular condition. var number = /^\d+/; var type = Object.prototype.toString.call(obj); for(var key i ...

Techniques for finding the total value of a JSON array

After retrieving values from a database, I am using them in JSON/javascript as an array. For example, see https://i.sstatic.net/nLzk9.png The issue arises when trying to calculate the sum of the array elements. I attempted to solve it with this code: v ...

What is the best way to incorporate an ASYNC function within a .map function to dynamically populate a table in a REACT application?

I am attempting to use the .map() method in REACT to call an async function and populate table data cells. The async function communicates with the backend of my application using data from the array being looped through. When called correctly, the functi ...

How to use the var keyword in JavaScript to declare block-scoped variables

At this moment, my goal is to establish a block-scoped variable in JavaScript by utilizing the var keyword. I prefer not to utilize the let keyword due to compatibility issues with certain browsers in ecma6. Is there an optimal and universal method to ac ...

How can we identify all the foreign_key1 ids from a MySQL join table that have a specific foreign_key2 assigned to them that is within a specified list?

I have a scenario where I have two tables, Table A and Table B, connected by a many-to-many relationship. Table A: ID --- 1 2 3 Table B: ID --- 4 5 6 7 Table AB: ID | A_ID | B_ID ---------------- 8 | 1 | 4 9 | 1 | 5 10 | 1 | 6 11 | 1 | 7 ...

Organizing a specific group of graph nodes in a unique layout with cytoscape.js

When working with Cytoscape JS, one can take advantage of the intriguing feature known as LAYOUTS. My goal is to organize a group of nodes in a circular layout. However, I do not wish for all the nodes in my network graph to be placed on that circle. Is t ...

Searching for a specific string within an array using JavaScript: tips and tricks!

I have a variable which looks like this: var d; d = [{'category': 'Hourly Report','from_start_datetime': '2013','format': 'yyyy-mm-dd hh:ii:ss', 'id': 'dateRangeTo'}] When I ...

Utilize ViewChild to handle changing elements in Angular 2 and Ionic 2 applications

I am facing an issue where I want to dynamically add multiple IonicSlides, but I am unable to use @viewChild. Can anyone suggest a solution for this problem? Template.html : <div *ngFor="let name of title;let i = index;"> <ion-slide ...

Developing AJAX Post Functionality Using Only Vanilla Javascript

Can I achieve AJAX Post in Pure Javascript without using the xmlhttprequest object? Consider a basic form like this: <form action="request.php" id="register_form"> <input type="text" name="first_name" placeholder="First Name"> <input t ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...

Uncertainty surrounding $q and commitments

After spending several hours researching Kris Kowal's Q library and the angularjs $q variable, I am still struggling to comprehend how it all works. Currently, my service contains the following code: resetpassword: function (email, oldPassword, newP ...

Implementing mouse event listeners on dynamically created elements in Vue.js

I've been curious if anyone has attempted something similar to the following code snippet (created within a Vue.js method): for (let i = 0; i < this.items.length; i++) { let bar = document.createElement('div'); bar.className = this ...