Not able to get value from postman response body - javascript

I have an API which has response as below:
"message": "Success!",
"user": {
"id": 17,
"first_name_kanji_or_hiragana": "Hiragana",
"last_name_kanji_or_hiragana": "Name",
"first_name_katakana": null,
"last_name_katakana": null,
"email": "user#example.com",
"image_path": null,
"email_verified_at": "2019-03-06 04:44:46",
"type": "admin",
"created_at": "2019-03-06 04:44:46",
"updated_at": "2019-03-06 04:44:46",
"deleted_at": null,
"full_name": "Name Hiragana",
"full_image_path": null,
"roles": [
Each time when i am running the API new user id is generating. What i want to do is that i want to fetch the id each time i run the api & then want to use that id in next response.
I have used below code to fetch the id but it's not working
pm.test(responseBody, true)
var jsonData = JSON.parse(responseBody);
jsonData.data.user[0].id

pm.test(responseBody, true)
var jsonData = JSON.parse(responseBody);
jsonData.data.user[0].id // youre access the user if its array its not
Just use jsonData.data.user.id or jsonData.data.user[id]

You are trying to access an array called user
jsonData.data.user[0].id
But user is an object, so you need to access:
jsonData.data.user.id
There are sometimes that you need to check the complete json directly from your request.

user is not an array. Try the below one.
jsonData.data.user.id
Your solution will work when you have the JSON like below,
"lib_folders": {
"changed": false,
"examined": 5,
"failed": false,
"files": [
{
"atime": 1549608521.3831923,
"ctime": 1548742613.5470872,
"path": "/root/abc/xyz",
"xusr": true
},
{
"atime": 1549608521.4031928,
"ctime": 1548742462.3279672,
"path": "/root/123/456",
"xusr": true
}
],
"matched": 2,
"msg": ""
}
For the above JSON if you want to get the path of the first file, then use the below code,
jsonData.data.lib_folders.files[0].path

Related

Update existing field in local json file in React Native

I'm working on an app where I have some data stored in the local JSON file. Initially, I'm showing that data using SectionList. And there are some fields to update the values of some fields of that data.
My data looks like this:
{
"title": "Terminal Settings",
"data": [
{ "title": "Keypad", "id": 1, "isSelected": false},
{ "title": "Menu", "id": 2 , "isSelected": false},
{ "title": "Tabs", "id": 3, "isSelected": false},
{ "title": "Mobile", "id": 4, "isSelected": false}
]
},
Now from UI, I want to change the status of isSelected field through the checkbox and also want to change it in the JSON file. So whenever I will access this data it should show isSelected: true.
How to do this? Do I need to use AsyncStorage for this?
I think you will definely have to open and modify the content of your file at some point, so your should need some filesystem. The best would be to simple get your json object with
const myData = require('./myDataJsonFile.json');
then modify it with for example $json[0]['data'][1]['isSelected'] = true
and finally save this in your file, replacing the file content with your $json

How to Iterate through each JSON key-value pair in Postman

I'm writing tests in POSTMAN against a POST API request by sending JSON body data of the following format:
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"activities" : null
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe"
}
}
I get Response for the request in similar format with some added details:
{
"status": "Success",
"message": "Created new 'Student' record",
"correlationCode": "Z848640-261354",
"type": {
"id": 51247,
"name": "Student",
"slug": "student",
"application": {
"name": "Willow University"
}
},
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe",
"name": "11206"
}
}
Now i want to achieve two things here:
1. Verify each key in response body does not have null value. Please note i'm sending one key with value as null and it is not returned in response.
2. The value sent in request body for each key is value returned by same key in response body. For instance if "name" key has value "Amber Joseph" then response key "name" also returns "Amber Joseph". But i want to do it for each key. Also Keys can defer everytime for instance i might or might not send it with "name" key hence i need a generic solution that applies to whatever key value pairs i send.
I'm able to loop through by using:
let jsonData = pm.response.json();
let dKey = Object.keys(jsonData);
let dValue = Object.values(jsonData);
for(var i = 0; i < dV.length; i++ ){
pm.expect(dV[i]).to.not.eql(null);
}
But this does not check nested key value pair individually.I specially want to check each key value pair inside the "data" object. Any help would be appreciated.
Thanks
You can grab the JSON data from the request like this:
const requestJson = JSON.parse(pm.request.body.raw);
(This assumes you're using a RAW body in Postman.)
Then, you can compare the response's data fields with the original request's data fields:
const requestJson = JSON.parse(pm.request.body.raw);
const responseJson = pm.response.json();
for (const [reqKey, reqValue] of Object.entries(requestJson.data)) {
pm.expect(responseJson.data[reqKey]).to.eql(requestJson.data[reqKey]);
}
From there, you can add whatever checks you want to do on the rest of the response.

How to check whether one node in API response has same value under all object using postman tests?

Suppose a API request fetches a users id, email address and their designated role. Sample API Request below:
GET: /v1/users HTTP/1.1
Content-Type: application/json
Authorization: bearer {access_token}
For the above request, the following is the response:
{
"content": [
{
"id": 1,
"email": "random#random.com",
"full_name": "AlbusDumbledore",
"role": "OWNER"
},
{
"id": 40,
"email": "random1#random1.com",
"role": "OWNER"
}
],
"last": false,
"total_elements": 2,
"total_pages": 1,
"sort": null,
"first": true,
"number_of_elements": 2,
"size": 20,
"number": 0
}
Now, what will be the test in postman to make sure that all the returned values under role node is equal to OWNER?
You could add something like a loop to check for it?
pm.test("Check role equals OWNER", () => {
var jsonData = pm.response.json()
for (i = 0; i < jsonData.content.length; i++) {
pm.expect(jsonData.content[i].role).to.equal('OWNER')
}
})
This should work to check the value of each role property, if the schema response you posted is correct.
I changed one of the values and ran the test again to show you it working - This will show the failure in Postman if the property is not equal to 'OWNER'.

reading an array of arrays of objects in ajax

I have three data coming back from an ajax call. I pack them into an array like this:
return json_encode([$salesOrder, $soAddressDetails, $lineItems]);
I then go to the view and look at the return. I see (as an example) this:
[
[{
"id": 8591,
"reference": "MYCLIENT",
"name": "MYCLIENT COMPANY \u00a3",
"allocated_status": "",
"created_at": "2016-12-02 09:31:00",
"order_date": "2016-12-02",
"cust_order_number": "",
"del_name": "",
"consignment": "",
"despatch_date": "0000-00-00",
"notes_2": ""
}],
[],
[{
"id": 11691,
"qty_ordered": 1,
"qty_delivered": 0,
"sales_order_id": 8591,
"due_date": "2016-12-30",
"stock_code": "ABC-ABDCDE-01",
"record_deleted": 0,
"updated_at": null,
"unit_price": 0,
"sales_order_item_id": null,
"comment": null,
"created_at": null,
"firmware_version": null,
"units_assigned": null
},
{
"id": 11692,
"qty_ordered": 1,
"qty_delivered": 0,
"sales_order_id": 8591,
"due_date": "0000-00-00",
"stock_code": "MISCELLANEOUS",
"record_deleted": 0,
"updated_at": null,
"unit_price": 232,
"sales_order_item_id": null,
"comment": null,
"created_at": null,
"firmware_version": null,
"units_assigned": null
}
]
]
In theory all I should need to access this, as array result is:
result[0] // sales order details
result[2] // line items = array of objects
so
result[0].reference == 'MYCLIENT'
and
result[2][0].stockcode == 'ABC-ABDCDE-01
but it won't let me do that. if I console.log(result[0]) the result is [, if I console.log(result[0][0].id) the result is undefined.
what am I doing wrong?
From the last line of your question, seems like your result is still a string.
Try doing JSON.parse(result)
Either you need to say that your response will be Json in your ajax like this
dataType: 'json'
Or after getting response you have to convert it into json object
response = JSON.parse(response);
I think you just miss the level. The reference it's also in a second level. So you need to access it like:
console.info(result[0][0].reference)

Iterate through nested Javascript Objects from API response

I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);

Categories