What's the best way to manipulate part of the response before sending it in a new request?

Hi,

I have a JSON that I get from the response of request1 and I want to manipulate the content of it and send it as a new request: request2.

Here’s how my sample JSON looks like:

 {
           "date": "",
          "vendor_name": "",
          "vendor_id": "", 
          "lines": [
                {
                    "line_description": "demo - test",
                    "line_detail": {
                        "ids": {
                            "abc_id": "34",
                            "def_id": "31201",
                            "account_id": "31201",
                            "account_name": "Dell"
                        },
                        "class": {}
                    },
                    "detail_type": "line_detail",
                    "line_id": "1",
                    "amount": 122.21,
                    "line_type": "",
                }
            ],
}

In my request I need to send one change at a time in the Lines array separately. I can store the Lines array in an environment variable but I want to first replace only the “line_description” value in that response while keeping the rest of the json the same and then in the third request (request3) with that value and modify the existing value for “abc_id”, and so on.

I was thinking of converting the response to XML and then manipulate the response but I learned that postman doesn’t support JSON to XML out of the box. So wondering if there’s a better way of handling it?

Note that I don’t have a predefined value I can use, I want to manipulate the value from existing response JSON and update one of the values before sending it. The question I have is more about how to manipulate the JSON than chaining the requests.

Hi @abhijeet ,

I think you may be able to do something like storing the response in the Postman sandbox, changing the value you want, and then saving it as a variable to use in subsequent requests. For example, if that’s the response you’re getting from an API call, you can write in the Tests tab:
var jsonResponse = pm.response.json();

Now you can do whatever you want with your jsonResponse object, including changing key values, removing fields, etc. From there, you can stringify that object and save it as a collection variable. Next, in the pre request script of your next request, you can use pm.collectionVariables.get('variable_name'), parse the stringified version of the variable, and you’ll have a JavaScript object you can work with and use the values of.

If it’s easier to see a hands on example, check out this public workspace I created that has two basic requests that goes through this workflow. You can modify it to your use case. Hopefully this helps!

3 Likes

Thanks Sean! That does the job for me :+1:

1 Like

Great news! I’m glad it was helpful :slight_smile:

Happy API testing!