POSTMAN: Comparing object Environment variable with response's object - javascript

I am having a problem with comparing object typed Env variable with the response's object in Postman even though it seems the same and couldn't find answers anywhere.
Here's the example:
The object used is:
"user":
{
"id" = 1,
"first_name": "John",
"last_name": "Smith"
}
When using a POST request I save the object as Environment Variable using:
var reqdata = JSON.parse(data.request);
postman.setEnvironmentVariable("User", JSON.stringify(reqdata.user));
and then in a GET response I want to compare it by using:
Pre-request Script:
user = JSON.parse(postman.getEnvironmentVariable("User"));
and then in Tests:
var data = JSON.parse(responseBody);
tests["user contains correct data"] = data.user == user;
console.log(data.user);
console.log(user);
The console.log returns exactly the same objects but I am still getting fail. I tried using Object.is() and === but it still returns fail. Could somebody please tell me what I am missing?
Cheers

I have found a solution, I've used:
tests["user contains correct data" = JSON.stringify(data.user) == JSON.stringify(user);
And I can also just delete the test script and use bare postman.getEnvironmentVariable instead of the second stringify().

You can find better solutions to your problem in a very similar question here:
How to write a postman test to compare the response json against another json?
I had a similar problem to solve except that my JSON also contained an array of objects.
My answer in this question or one of the other answers will provide a more stable solution for comparison.
I created an array of global functions called "assert", which contained helper functions such as "areEqual" and "areArraysOfObjectsEqual" and saved these under the "Tests" tab at a top folder level of my tests.

Related

JSON object recieved from api property returns undefined

For the project that I am working on, I am using the Shopify API which allows you to retrieve products and other information from your store to be retrieved in the format of a JSON object. I was able to successfully get the JSON object from the API, however when I try to access a property of the JSON object, it returns undefined. I have looked at a couple of articles that I will refrence below, but the problem for those users were things such as needing to use:
JSON.parse()
for a JSON object enclosed by strings which is not my probelem, I have tried a few other work arounds as well but with no luck, I originally thought that the problem was that my code needed to use an "Async/Await" function in order to wait for a response from the API, but I then realized that wouldn't make sense considering I can recieve the whole JSON object itself with no problems.
When I use:
request.get(url, {headers})
.then( result => {
console.log(result); // Only accessing object itself
});
I recieve the JSON object response correctly with no error like this:
{"products":[{"title":"Test Product 1","body_html":"This is a product that is being tested for retrieval!",
"product_type":"","created_at":"2018-08-21T17:49:07-07:00","handle":"test-product-1","updated_at":"2018-08-21T17:49:07-07:00","published_at":"2018-08-21T17:48:19-07:00","template_suffix":null,"tags":"",
"published_scope":"web","variants":[{"title":"Default Title","price":"5.00","sku":"","position":1,"inventory_policy":"deny",
"compare_at_price":null,"fulfillment_service":"manual","inventory_management":null,"option1":"Default Title","option2":null,"option3":null,
"created_at":"2018-08-21T17:49:07-07:00","updated_at":"2018-08-21T17:49:07-07:00","taxable":true,"barcode":"",
"grams":99790,"image_id":null,"inventory_quantity":1,"weight":220.0,"weight_unit":"lb","old_inventory_quantity":1,
"requires_shipping":true,}],"options":[{"name":"Title","position":1,"values":["Default Title"]}],"images":[],"image":null}]}
However when I use this, the JSON object property returns undefined:
request.get(url, {headers})
.then( result => {
console.log(result.products[0]); // Accessing the first item in JSON "products" array
});
Articles I have already checked out:
cannot access json object property returns undefined
JSON object returns undefined value
JSON objects returns undefined
Would anyone be able to explain my error or why this is happening? I am more than happy to edit my question to include any code/information that might be helpful.
Thanks in advance,
Michael
try this:
console.log("data:", JSON.stringify(result.products[0], null, 2));
console.log to print the result to your console. Use Chrome and developer tools and you will see a console option - excellent for debugging.
JSON.stringify turns the JSON data into something you can see and read. You can convert the data and then split as you need this way too.
OK, a second answer. I can't check this, as I don't have your JSON data, however, I would try something that would likely resemble this...
data.Items[0].field
if the data is not correctly formatted then take the stringify approach and split it out. Otherwise, consider this:
products":[{"title":"Test Product 1"
variable = products[0].title;
I would tend to use a function to pull all the data out in one shot.
function Getv(data){ global.myApp.v = JSON.stringify(data, null, 2); }
then I might run this...
Getv(data.Items[0]); let splitData = global.myApp.v.split('\"'); let vCount= splitData.length;
if the object returns like this it wouldn't work because it's missing a colon after "products" identifier. like Luca said it's not a valid JSON response
Try this:
var resultJson = JSON.parse(result);
console.log(resultJson.products[0].varname);

JSON.stringify turned the value array into a string

I have a JS object
{
aString:[aNumber, aURL]
}
JSON.stringify() returns
{
"aString":"[number, \"aURL\"]"
}
I thought that valid JSON can have arrays as values. Can I have stringify return the JSON string without converting the array into a string? Basically I need turn the whole JS object straight into a string, without any modification.
Is there a better way to do this? I've been looking around but everyone suggests using JSON.stringify if I want an object to string, and no one has raised this problem.
EDIT: Thanks for the quick responses. Here is how I created my JS object, please let me know if I messed up and how!
cookie = {};
// productURL is a string, timer is a number, imageSrc is a URL string
cookie[productURL] = [timer, imageSrc];
// then, I just stringified cookie
newCookie = JSON.stringify(cookie);
If it is also relevant, I am setting an actual cookie's value as the resulting JSON string, in order to access it in another set of functions. Setting the cookie's value does do some URI encoding of its own, but I've actually been grabbing the value of newCookie in the Chrome console as well and it also returns the Array as a string.
If an object you're trying to stringify has a toJSON function, that will be called by JSON.stringify. Most likely you have an external library that's adding Array.prototype.toJSON.
For example, an old version (1.6) of Prototype JS will "conveniently" add that for you.
Prototype 1.6.1:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Whereas a newer version will not.
Prototype 1.7.2:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.min.js"></script>
You could try deleting Array.prototype.toJSON just to see if that's what's causing the problem. If it is, you might want to look into upgrading/deprecating any libraries in your code that do weird things like that.
Prototype 1.6.1 (after deleting toJSON)
delete Array.prototype.toJSON;
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Based on your description this is not what should happen.
If you have code like this:
var obj = {
aString:[123, "test"]
}
document.getElementById("out").value = JSON.stringify(obj);
it will generate the expected json:
{"aString":[123,"test"]}
also see https://jsfiddle.net/zudrrc13/
in order to produce your output the original object would have to look something like:
var obj = {
aString:"[123, \"test\"]"
}

Procjess JSON of unknown Formats

a Services provides the following Information via JSON
{"errors":{"subject":"foobar"}}
and further alements in this errors array
OR
{"ok":{"subject":"foobarfoobar"}}
and further alements in this ok array array
So always either of the two is present, not both at once. Any as one is not present I always get an access error as one the proeprties is of course not existing
And I completely fail how to process this result. I always get "can not ... of undefined":
Currenlty I have:
if (data[0].hasOwnProperty("status")) {
alert('ddd');
}
What is the correct way to test, if either errors or ok is provided?
UPDATE
blex is right: But on the serverside is use:
echo json_encode( array('errors' => $result['errors']) );
Doesnt this mean I that errors is already the first element of an array? Why is this seen as an object propety?
SOLUTION/LEARNING:
Beware of PHP! As stated above echo json_encode( array('errors' => $result['errors']) ); does NOT lead to encoding this as an JSON Array. What I missunderstood and oversaw was, that { is the Format/Notation for Objects NOT for Arrays. So to be an array it would have to be [ . So in the End PHP does encode Associative Arrays as normal Object Properties not as arrays. That was my wrong assumption
var x = { "errors": { "subject": "foobar" } };
//var x = { "ok": { "subject": "foobarfoobar" } };
if (x.errors) {
} else if (x.ok) {
}
Essentially, you're already on the right track. hasOwnProperty is the right way to check for the existence of these keys.
I'm not sure what language you're using, but it seems like json_encode is converting your array to a single object, then putting that object under the errors key.
One last thing, you should probably look into using HTTP response codes. If you can return a 200 OK for the okay scenario, and a 400 or 500 level code for your error, then you'll be able to use better methods of determining how to process these situation. jQuery.ajax has the ability to put two handlers in place, one for success and one for failure, for instance.

How to get data from JSON response?

I am using plain JavaScript on my project. How can I get the value of the following example with the category? I need to detect whether it comes back true or false.
{
"category": "true"
}
I can get the entire object, but I just want to pull out the value of category.
from comment...
The JSON data is returned from the server based on a form submission. It keeps saying myObject is undefined. How can do I pass this so my JavaScript can read the response?
from comment...
I can get myObject using this: if (form.XHR.status === 200) {var data = form.XHR.response;}, but if I try to do data.myObject it says it's undefined.
You need to parse the JSON before you can access it as an object...
if (form.XHR.status === 200) {
var data = form.XHR.response;
var parsed = JSON.parse(data);
alert(parsed.category);
}
Why is this needed? It's because JSON is not JavaScript. The two terms are not synonymous.
JSON is a textual data interchange format. It needs to be parsed into the data structures of whatever language it's been given to. In your case, the language is JavaScript, so you need to parse it into JavaScript data.
When it is received form the xhr response, it is received in the form in which all textual data is handled in JavaScript. That is as a string. As a string, you can't directly access the values represented.
JavaScript has a built in parser called JSON.parse. This was used in the example above to do the necessary conversion.
Some older browsers don't support JSON.parse. If you're supporting those browsers, you can find a JavaScript parser at http://json.org .
First of all you need a variable to refer it:
var obj = {
"category": "true"
};
Then can you say e.g:
alert(obj.category);
var myObject = { "category": "true"};
alert (myObject.category);
But you likely want:
var myObject = { "category": true};
...if you're going to be testing for true/false:
if (myObject.category) {
// category is true, so do your stuff here.
}
You can access json object data using '.' or [key] like this :
var obj = {
"category": "true"
};
console.log(obj.category);
// Or
console.log(obj["category"]);
Here is the DEMO
For anyone who arrives here banging their head against the wall, make sure to see if you need to access a parent object which wraps all the delivered data:
console.log(response['id'])
may not work, because a parent entity must be accessed first:
console.log(response.session['id'])
If you console log your response and it is wrapped in {} you probably need to do this.

How do I add JSON object as new level to another JSON object?

I have a code that gets in the end collection of two JSON objects, something like this.
var jsonL1 = {"holder1": {}}
var jsonL2 = {"section":"0 6","date":"11/12/13"}
I would like to insert jsonL2 inside jsonL1.holder1 and merge it to one JSON object.
Desired output
{
"holder1": {
"section": "0 6",
"date": "11/12/13"
}
}
How can I do that?
It is as easy as:
L1.holder1 = L2
I removed the "json" from the variable names, as #patrick already said, you are dealing not with "JSON objects" but with object literals.
See also: There is no such thing as a JSON object
You also might want to learn more about objects in JavaScript.
If you want the first object to reference the second, do this:
jsonL1.holder1 = jsonL2;
If you wanted a copy of the second in the first, that's different.
So it depends on what you mean by merge it into one object. Using the code above, changes to jsonL2 will be visible in jsonL1.holder, because they're really just both referencing the same object.
A little off topic, but to give a more visual description of the difference between JSON data and javascript object:
// this is a javascript object
var obj = {"section":"0 6","date":"11/12/13"};
// this is valid JSON data
var jsn = '{"section":"0 6","date":"11/12/13"}';

Categories