0

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

1
  • 1
    what about console.log(response.part + "=" + ids); Commented Oct 20, 2022 at 1:35

1 Answer 1

1

@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}`))
Sign up to request clarification or add additional context in comments.

1 Comment

this was very helpful. I am new to Postman and JS and I was not aware at first that map() is an iterator and so I assumed I would also need that to grab the 'sku'. Your explanation made perfect sense, and yes, I have multiple 'id' in my response body.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.