Get data from request body in postman

Hi
My request body is :

query{
and[
{
        "gender": 1,
        "company": "MyCompany",
        "name": "Doe",
        "firstname": "John",
        "phone": "0606060606" 
},
{
 "gender": 1,
        "company": "MyCompany",
        "name": "Doe",
        "firstname": "John",
        "phone": "0606060606" 
}
]
},
"sort": {
"firstname": john,
"phone": "0606060606" 
}

}


I want to access firstname value from query block .
Const body = JSON.parse( pm.request.body.raw);

Getting whole body in row.

How to fetch specific value from request body .

1 Like

You appear to have an array, with more than one record.

Which firstname do you want to retrieve?

That also doesn’t look like valid JSON! What is the query bit at the top? Is this a GraphQL request?

If you console log the body variable. Can you show us a screenshot of the result? (With all of the elements expanded out).

Const body = JSON.parse( pm.request.body.raw);
console.log(body);
Console result :-
{query: {...}, sort [1]...}

After expanding above  got below 
query:{...}
sort: [1]

After expanding got this
query:{ ...}
and: [2]
0:{...}
1:{...}

After expanding 0

0: {...}
      gender": 1,
        "company": "MyCompany",
        "name": "Doe",
        "firstname": "John",
        "phone": "0606060606" 

1:{...}

I want to get “name” value from request body in my script . name or firstname from query block from request body .

Try console logging the keys.

const body = JSON.parse(pm.request.body.raw);
console.log(body.query.sort[0].and[0].firstname)

If this doesn’t work then the console log the keys one at at time.

const body = JSON.parse(pm.request.body.raw);
console.log(body)
console.log(body.query)
// etc

It appears that your body returns an object with the top level key called “query”.

This has an key called “sort” with one value in it. You target array elements by their index number, where the indexes start at 0. So it will be sort[0].

Within the sort array, there is another array called “and” with two values in it.

Please note, you have more than one record with the same data. Is this correct? Which firstname do you need to target. and[0] or and[1].

Once you are passed this element, it looks like you should be able to target your firstname key.

console.log(body.query.sort[0].and[0].firstname)
1 Like

@raniakanksha22 , If you are new to APIs, handling and parsing the complex JSON responses might sound challenging. But you can master this if you learn more about the JSON structure. Since you pasted the
response as image, its’ hard to locate the first name. Also seems like its an array.

You can paste your response in https://jsonpathfinder.com/ and it gives you the xpath. that tool is pretty straightforward. If so, feel free to read my blog which I wrote long back.

Good Luck :slightly_smiling_face: