Asserting the values in JSON response through tests in Postman - json

My JSON response body looks like :
[
{
"_time": "1499996827804",
"properties": {
"length": "80",
"width": "4500"
}
}
]
I am using Postman to write tests to assert on value of length and width and _time.
I wrote :
var data = JSON.parse(responseBody);
tests["Check length value"] = data.length === "80";
But it's failing. Can anyone help ?

If your JSON looks like this:
[ { "_time": "1499996827804", "properties": { "length": "80", "width": "4500" } } ]
Then you need to fix the data.length === "80" part of your test.
Firstly, your JSON is an array, so you need to be selecting data[0] to get the first item in the response (which is { "_time": "1499996827804", "properties": { "length": "80", "width": "4500" } }). Then, it looks like you're trying to check the length part of the response, which is under the properties object. So your selector should now look like this: data[0].properties.
And finally, to access the length part, add .length to the end of your selector: data[0].properties.length.
Put it all together, and you should have:
tests["Check length value"] = data[0].properties.length === "80";
Hope it helps!

Your data is coming back in an array so you need to get the first item of the array. Also length is a sub property of the "properties" object. Try this:
tests["Check length value"] = data[0].properties.length === "80";

Related

how to remove [] character at extracted json using json path

{
"responseCode": "200",
"data": {
"sequence": 1,
"used": true,
"sensingTags": [
{
"code": "LED",
"value": 1,
"updatedOn": 1587557350251
}
]
}
}
My goal is get updatedOn value from this json using jsonPath like this
1587557350251
i thought below jsonPath will work but it extract only empty list.
$..sensingTags[?(#.code == 'LED')][0].updatedOn
And i want to know how to extract value like below
{
"code": "LED",
"value": 1,
"updatedOn": 1587557350251
}
Not like this one.
[
{
"code" : "LED",
"value" : 1,
"updatedOn" : 1587557350251
}
]
As per Getting a single value from a JSON object using JSONPath, JsonPath will always return an array (or a false) at that point...
Best you can do is process it as an array of updatedOn and simply always grab the first value.
$..sensingTags[?(#.code == 'LED')].updatedOn

Not able to fetch the value of a key from JSON data

I am trying to fetch value if "id" from JSON response I got from a POST request.
{
"callId": "87e90efd-eefb-456a-b77e-9cce2ed6e837",
"commandId": "NONE",
"content": [
{
"scenarioId": "SCENARIO-1",
"Channel": "Channel1-1",
"data": {
"section": {
"class": {
"repository": [
{
"export": "export-1",
"modules": "module-1",
"index": "23",
"period": {
"axis": {
"new_channel": "channel-1.1"
},
"points": [
{
"id": "6a5474cf-1a24-4e28-b9c7-6b570443df9c",
"duration": "150",
"v": 1.01,
"isNegligible": false
}
]
}
}
]
}
}
}
}
]
}
I am able to display the entire response json and am also able to get the value of "callId" using below code. Getting error at last line:
Cannot read property '0' of undefined
Code snippet:
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
let responseData = JSON.stringify(body);
//Display the entire response
console.log(responseData);
//Display the callId
console.log(body['callId']);
//Getting error here
console.log(body.content[0].repository[0].points[0].id);
}
}
Any solution to get value of "id" ?
Right now you are trying to log body.content[0].repository[0].points[0].id).
If you look at it carefully the repository[0] is an object and it has no immediate child points.
So repository[0].points would evaluate to undefined and by specifying repository[0].points[0], you are trying to access property 0 of undefined as the error states.
The correct way of accessing id would be as follows :
body.content[0].data.section.class.repository[0].period.points[0].id
If you have confusion regarding parsing JSON try breaking it down by consoling body and then by expanding it in the console or in JSONeditor
PS: It is also recommended that you check at each level if the value exists before trying to access a deeper child elements, since in some cases your body may not contain one of the values, say content for example. In that case trying to access body.content[0] will cause an error. So it is recommended to do checks at each level like follows
if(body){
if(body.content){
if(body.content[0]){
/* and so on*/
}
}
}
Try with
console.log(body.content[0].data.section.class.repository[0].period.points[0].id)

Updating nested array n1ql

The sample doc, I am trying to work with is:
{
"name": "level1",
"childLevel1": [
{
"name": "level2",
"childLevel2": [
{
"name": "level3",
"childLevel3": [
{
"name": "level4",
"attribute1": "data"
}
]
}
]
}
]
}
What we want to do is, with n1ql add one more array element to "childLevel3". I have tried the reference to https://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/update.html
I was able to add a regular attribute to childLevel2 but after that it was not working. This is the query I have been trying out.
Update sample
set child2.childLevel3 = ARRAY_PUT(child2.childLevel3, {'attribute' : 'data2'})
FOR child2 in child1.childLevel2 when child2.name == "level3" END
for child1 in childLevel1 when childLevel1.name == 'level2' END
WHERE name == 'level1'
But it gives me error on parsing, I tried other ways too but nothing works.
Try
UPDATE sample
SET child2.childLevel3 = ARRAY_PUT(child2.childLevel3, {'attribute' : 'data2'})
FOR child2 in child1.childLevel2
FOR child1 in childLevel1
WHEN childLevel1.name == 'level2' AND child2.name == "level3"
END
WHERE name == 'level1';
I had to update an object within a nested array, recently in Couchbase. The answer above helped me to formulate this query in a bucket called "metadata". The data structure is:
{
"documentMetadata": {
"documentId": "42"
},
"results": [
{
"type": "FileStaging",
"status": "NOT STARTED"
}
],
"type": "runLog"
}
The query that worked for me:
UPDATE metadata
SET res.status = 'QUEUED'
FOR res in results
WHEN res.type = 'FileStaging'
END
WHERE type = 'runLog'
AND documentMetadata.documentId = '42'

How to check JSON request body for REST Api, for object attributes and structure?

I am writing my first api (express/node) and one of the endpoints receives json data in the body like:
{
"text": "some comment here...",
"tags": [
{"id": 0, "tag": "some tag 1"},
{"id": 123, "tag": "some tag 2"}
],
"date": "1452305028289",
}
Is there some way you can check that all the properties exist on the object and that they have values? Or do you have to write a custom function checking for each required property and values?
You can use one of these packages for validating data with NodeJS:
https://github.com/hapijs/joi
https://github.com/mafintosh/is-my-json-valid
https://github.com/ctavan/express-validator
A simple solution would be this function that takes an object and a list of strings as the properties of that object:
var checkProperties = function (obj, props) {
return props
.map(function(prop) { return obj.hasOwnProperty(prop); })
.reduce(function (p, q) { return p && q; });
}
use like this
checkProperties({ prop1: someValue, prop2: someOtherValue }, ["prop1", "prop2"]); // true

JSON values exists?

I want to build a script which get s a JSON and manipulates it.
I have one problem, i don't know how to check if a certain value exists, for example:
i get this JSON when doing action 1:
{
"url": "http://zuberi.me",
"top": "true"
}
and when i do action 2:
{
"url": "http://zuberi.me",
"top": "true",
"copy": "false"
}
so i want to check if "copy" is exists in the JSON response i get...
thanks in advance :)
A javascript implementation:
var json1 = { "url": "http://zuberi.me",
"top": "true",
"copy": "false" },
json2 = { "url": "http://zuberi.me",
"top": "true" };
json1.hasOwnProperty('copy'); // true
json2.hasOwnProperty('copy'); // false
Assuming that your JSON string is already converted to a JavaScript object:
if ("copy" in json) {
// ...
}
if (typeof(json.copy) === 'boolean') {