11

I have a test in Postman where I do a post request and need to parse the json response

The response looks like this:

"aPIProxy" : [ {
    "name" : "SFDC-UpdateLoginTime-v1",
    "revision" : [ {
      "configuration" : {
        "basePath" : "/",
        "steps" : [ ]
      },
      "name" : "1",...some attributes}]

and i need to get something like :

"name" : "SFDC-UpdateLoginTime-v1"
"name" : "1"

for a multiple occurrence json file.

1
  • 1
    What do you need to do with it once you have the correct format? Store it as a variable or just log it yo the console? Take a look at the _. map() function of lodash to get what you need - lodash.com/docs/#map Commented Jun 25, 2018 at 21:30

3 Answers 3

10

The below postman script might help you.

var jsonData = JSON.parse(responseBody);
var jsonNamesData = jsonData.aPIProxy;
console.log(jsonNamesData);
var parsedData = "";
for(var i=0;i<jsonNamesData.length;i++){
    parsedData = parsedData +"\"name\" : \"" +jsonNamesData[i].name+"\", ";
    console.log("\"name\" : \"" +jsonNamesData[i].name+"\"");
}
console.log(parsedData);
postman.setEnvironmentVariable("parsedNamesResponse", parsedData); // updating parsed data to the environment variable parsedNamesResponse
0
8

You could capture multiple 'name' properties using the _.map() function of Lodash, which is a built it module on the native application. I've had to modify what you need slightly as the name key would have been a duplicate.

const result = _.map(pm.response.json().aPIProxy, data => ({
  name: data.name,
  revisionName: data.revision[0].name
}))

pm.environment.set("response", JSON.stringify(result))

This would then store all the values in an environment variable for you to use elsewhere in another request.

Postman

0

You should first parse the response using JSON.parse, then you can iterate on the parsed object like:

var resObj = JSON.parse(pm.response.text())
for(var i=0; i< resObj.length; i++) {
    console.log("name: "+ resObj[i].name);
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.