Parsing JSON data from Postman - json

I am trying to parse a JSON response from Postman that is not cooperating. Here is the body response:
{
"teams": [
{
"id": "MI6",
"name": "James Bond's Workspace",
"color": "#04a9f4",
"avatar": null,
"members": [
{
"user": {
"id": 007,
"username": "James Bond",
"email": "blahblah#gmail.com",
"color": "#e65100",
"profilePicture": null,
"initials": "JB",
"role": 1,
"custom_role": null,
"last_active": "1609978205632",
"date_joined": "1609897014429",
"date_invited": "1609897014429"
}
}
]
}
]
}
I am using the following test scripts that can't seem to resolve the [ value after teams.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("teams_id", jsonData.teams.id);
postman.setEnvironmentVariable("teams_id", jsonData.teams.user.id);
It is creating the variable for me, but will not store the value of MI6 or the value of 007.

You're trying to access values that are in an object, inside an array.
Specifying the object you need with [0] because it's the first object in the array, will get the value. You would also need to do the same with members.
This should be what you need:
var jsonData = pm.response.json();
pm.environment.set("teams_id", jsonData.teams[0].id);
pm.environment.set("user_id", jsonData.teams[0].members[0].user.id);

Danny thanks for your response. I found another thread about parsing json data from an array and used this response to fix the issue. Here is what worked:
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.teams.length; i++) {
var teams_id = jsonData.teams[i];
console.log(teams_id.id);
console.log(teams_id.name);
postman.setEnvironmentVariable ("teams_id",teams_id.id)
postman.setEnvironmentVariable ("teams_name",teams_id.name)
}

Related

How do i get a specific data from responseBody on postman

I'm trying to set an environment variable using the following:
var data = JSON.parse(responseBody);
pm.environment.set("petId", data.id);
And this is what is in my response:
{
"id": 9222999990497629102,
"category": {
"id": 0,
"name": "dog"
},
"name": "Brutus",
"photoUrls": [
"http://placeimg.com/640/480"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}
But somehow my environment looks like this:
"petId": "9222999990497629000"
I don't where from where I'm getting these last zeros on my variable.
pm.environment.set("petId", JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id);
As the id is a big int greator than MAX_SAFE_Integer , the response will be rounded when parsed as JSON. It is a javascript behavior.
You can enclose it with double quotes. After that extract that id.
now if you want to convert id to number use BigInt
let id = JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id
id = BigInt(id)
console.log(id)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

SwiftyJSON not working with WebSocket message

I have a socket response that is this:
{"op":0,"d":{"author":{"id":"6699457769390473216","name":"Test","verified":false},"unixTime":1597277057132,"id":"6699465549836976128","group":"64632423765273287342","content":"Yo","_id":"5f34838198980c0023fa49e3"},"t":"MESSAGE"}
and I need to access the "d" object, I've tried doing
print(JSON(data)["d"])
and it just Returns null every time.
If data is of type String, you are probably using the wrong init method to initialize the JSON object. Try using init(parseJSON:) like this:
let jsonString = """
{
"op": 0,
"d": {
"author": {
"id": "6699457769390473216",
"name": "Test",
"verified": false
},
"unixTime": 1597277057132,
"id": "6699465549836976128",
"group": "64632423765273287342",
"content": "Yo",
"_id": "5f34838198980c0023fa49e3"
},
"t": "MESSAGE"
}
"""
let json = JSON(parseJSON: jsonString)
print(json["d"])

JSON transformation in node.js

I want to transform my data from one json structure to another. What is the best way to do it?
Here is my original resource (customer) structure is:
{
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
I want to change it to:
{
"id": "123",
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
Keeping in mind that I might have an array of resources(customers) being returned in GET /customers cases. I want to change that to an array of new data type.
If customer object is array of object then below will help you to get desire format result
var result = customerObj.map(x => {
return {
id: x.id,
name: x.data.name,
status: x.data.status,
contacts: x.data.contacts
};
});
here I have used Object.assign() it will be helpful to you
var arr={
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
arr=Object.assign(arr,arr.data);
delete arr['data'];
console.log(arr);
You have to Json.parse the json into variable, and then loop through the array of objects, changes the object to the new format, and then JSON.stringify the array back to json.
Example code
function formatter(oldFormat) {
Object.assign(oldFormat, oldFormat.data);
delete oldFormat.data;
}
let parsedData = JSON.parse(Oldjson);
//Take care for array of results or single result
if (parsedData instanceof Array) {
parsedData.map(customer => formtter(customer));
} else {
formatter(parsedData);
}
let newJson = JSON.stringify(parsedData);
console.log(newJson);
Edit
I made the formatter function cleaner by using Kalaiselvan A code

Extract value from array of objects in Postman

I want to extract Id value from the array with objects in Postman and then set it as an environment variable. In case JSON response is an object, the following script works, but not with an array of objects (my array has only one object).
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data.Id);
JSON response:
[
{
"Id": 1287,
"LastName": "Trump",
"FirstName": "Donald",
"MiddleName": "Von",
"City": "New York City",
"Phone": "66 77 88",
"State": "New York",
"Fax": "111-222-333",
"ReferenceId": "12345",
"Active": false,
"CurrentWorkingSchemeId": null
}
]
If it is an array of objects, then just select the first object using index [0] before grabbing the object's key like this:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("userid", data[0].Id);
This works like charm!
Basically what i am doing here is, parse the response and from the data array, take id and save it in postman environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++) `
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}

json object accessing

i know its very simple thing but i m stucked on it
i have json variable with data as follow
var jsonText =
'[ { "user": [ { "Gender": "M", "Minage": "19", "Maxage": "30", "MaritalStatusId":"0", }]
},
{ "user":[ { "maritialtype": "Does not matter" }]
},
{ "user": [ { "Value": "No" }]
} ]';
var jsonObject = JSON.parse(jsonText);
now i can access gender as jsonObject[0].user[0].Gender
but i'm not able to access maritialtype and Value
For maritialtype:
jsonObject[1].user[0].maritialtype
For Value:
jsonObject[2].user[0].Value
Because you have an array of three objects, user, which is an array or one object. It's kind of a weird structure.