Home > Back-end >  How to extract specific values from JSON response in Postman and concatenate
How to extract specific values from JSON response in Postman and concatenate

Time:10-21

I need to be able to do the following in Postman

  1. Parse through a JSON response
  2. Retrieve specific values: some nested, some not
  3. (optional) Concatenate the final result

I can currently perform 1 and I can accomplish 2 for one specific value with the help of this explanation link

What I can't do is retrieve two values. Below is the sample response I am working with

{
    "part": "9FH74T00",
    "summaries": [
        {
            "id": "A1AGQF32TR"
        }
    ]
}

I was able to modify the JS from the link above to extract the nested id value

var response = JSON.parse(responseBody);
var ids = response.summaries.map(function(summary) {
  return summary.id;
});
console.log(ids);

How can I expand on the JS to also retrieve the part value and ideally output that in the console as part = id or 9FH74T00 = A1AGQF32TR

CodePudding user response:

@lucas-nguyen's seems a valid response/comment to what you propose. What is not well explained is the model. summaries is an array so would you get multiple ids? The fact that you use a map makes me thing there will be multiple ids.

part = id1,id2,id3

or

part = id1
part = id2
part = id3

I've created a sample request with your payload and two ids in summaries. I've console.log 3 approaches:

  1. single part and single id
  2. single part and ids in a list
  3. single part and ids in tuples

So with the example response:

{
"part": "9FH74T00",
"summaries": [
      {
        "id": "A1AGQF32TR"
      },
      {
        "id": "SECONDID"
      }
    ]
}

You would get the following output:

 Option 1:
 
9FH74T00 = A1AGQF32TR
 

Option 2, list of ids:
 
9FH74T00 = A1AGQF32TR,SECONDID
 

Option 3, list of ids:
 
9FH74T00 = A1AGQF32TR
 
9FH74T00 = SECONDID

If for some reason you can't open the example, this is my test tab:

const response = pm.response.json().data;

// Just concatenate single part and single id
console.log("\nOption 1:")
console.log(`${response.part} = ${response.summaries[0].id}`)

// Co
console.log("\nOption 2, list of ids:")
const ids = response.summaries.map( x => x.id)
console.log(`${response.part} = ${ids.join(",")}`)

console.log("\nOption 3, list of ids:")
ids.forEach( x => console.log(`${response.part} = ${x}`))
  • Related