I want to validate a Nested JSON Schema in Postman.
Here is the code.
const testSchema = {
"name": [
{
"first_name": "Alpha",
"last_name": "Bravo"
},
{
"first_name": "Charlie",
"last_name": "Delta"
},
],
"age": "23",
"color": "black"
};
const showData = {
"required": ["name", "age"],
"properties": {
"name": [
{
"required": ["first_name"]
}
],
},
};
pm.test("Nested Schema Test", function () {
pm.expect(tv4.validate(testSchema, showData)).to.be.true;
});
Currently, this code returns test as true.
I am unable to test the "name" array objects' keys.
Even upon passing this:
"required": ["fst_nae"] //wrong key name
it returns true.
I would just check in easy way via:
pm.test("your name", function () {
pm.expect(testSchema.name[0].first_name && testSchema.name[1].first_name
).to.eql('Alpha' && 'Charlie')
});
and you successfully validated these fields
or use this expect to organize your code of your choice
tiny validator i.e. tv4.validate is having issues in their library. Another option is to use AJV (you can search it on github).
Related
I want to learn how to use Lodash to extract variables from a JSON response because the traditional methods explained on other Postman questions do not explain an easy way to do this as I used to do it with json path in Jmeter.
I need to translate the following json paths to a Lodash expression that returns the same values as this JSON paths
1. FlightSegmentsItinerary[*].Flights[*].Key
2. $..Flights[*].Key
3. Travelers[*].[?(#.TypeCode == "INF")].FirstName (returns the name of the passangers whose type code are == "INF")
JSON Response:
{
"Travelers": [
{
"TypeCode": "ADT",
"FirstName": "FULANO",
"Surname": "LAZARO",
"Key": "1.1"
},
{
"TypeCode": "INF",
"FirstName": "MENGANO",
"Surname": "XULO",
"Key": "2.2"
}
],
"FlightSegmentsItinerary": [
{
"Flights": [
{
"Key": "1"
},
{
"Key": "2"
}
]
}
]
}
So far I was able to extract the travelers Keys (Travelers[*].Key) using this:
var jsonData = pm.response.json();
var travelerKeys = _.map(jsonData.Travelers, 'Key');
console.log("travelerKeys: " + travelerKeys);
Output: travelerKeys: 1.1,2.2
As you can see, the JSON path:
Travelers[*].Key
Looks like this in Lodash:
var travelerKeys = _.map(jsonData.Travelers, 'Key');
for this case.
var jsonData = {
"Travelers": [{
"TypeCode": "ADT",
"FirstName": "FULANO",
"Surname": "LAZARO",
"Key": "1.1"
},
{
"TypeCode": "INF",
"FirstName": "MENGANO",
"Surname": "XULO",
"Key": "2.2"
}
],
"FlightSegmentsItinerary": [{
"Flights": [{
"Key": "1"
},
{
"Key": "2"
}
]
}]
}
// 1. FlightSegmentsItinerary[*].Flights[*].Key
console.log( _(jsonData.FlightSegmentsItinerary).flatMap('Flights').map('Key') )
//2. $..Flights[*].Key
console.log( _.chain(jsonData).values().flatten().find('Flights').values().flatten().map('Key') )
//3. Travelers[*].[?(#.TypeCode == "INF")].FirstName (returns the name of the passangers whose type code are == "INF")
console.log( _(jsonData.Travelers).filter(['TypeCode', 'INF']).map('FirstName') )
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js"></script>
Another option might be to try JavaScript libraries such as https://github.com/dchester/jsonpath
var jsonData = {
"Travelers": [{
"TypeCode": "ADT",
"FirstName": "FULANO",
"Surname": "LAZARO",
"Key": "1.1"
},
{
"TypeCode": "INF",
"FirstName": "MENGANO",
"Surname": "XULO",
"Key": "2.2"
}
],
"FlightSegmentsItinerary": [{
"Flights": [{
"Key": "1"
},
{
"Key": "2"
}
]
}]
}
console.log(jsonpath.query(jsonData, '$.FlightSegmentsItinerary[*].Flights[*].Key'))
console.log(jsonpath.query(jsonData, '$..Flights[*].Key'))
console.log(jsonpath.query(jsonData, '$.Travelers..[?(#.TypeCode == "INF")].FirstName'))
<script src="https://cdn.jsdelivr.net/npm/jsonpath#1.0.2/jsonpath.min.js"></script>
Because Postman doesn't support fetch and XMLHttpRequest, the jsonpath.min.js file contents can be saved in environment variable, and then eval(pm.environment.get('jsonpath')); before use as described in
https://community.getpostman.com/t/adding-external-libraries-to-postman/1971/4
You have to tell Postman which Sandbox module you going to use using require function(refer below code). The error you get has some issue with Postman few of them works few of them not Here they are talking
and Here is the postman issue tracker
the code I tried and worked for me as
const moment = require('lodash');
var keys = _.chain(obj.Travelers)
.map("Key")
.flatten()
.unique()
.value();
console.log(keys);
output
Array:[]
0 : "1.1"
1 : "2.2"
form more details you can look at
Postman Sandbox API reference
postman-and-lodash-the-perfect-partnership
I have the following schema for bellow happy path response
var responseSchema =
{
"type": "object",
"properties": {
"value": {
"type": "object",
"properties":{
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"patientGuid": {"type": "string" },
"givenName": {"type": "string" },
"familyName": {"type": "string" } ,
"combinedName" : {"type": "string" }
},
"required": ["patientGuid","givenName","familyName"]
}
}
}
}
}
};
Happy path response:
{
"value": {
"items": [
{
"patientGuid": "e9530cd5-72e4-4ebf-add8-8df51739d15f",
"givenName": "Vajira",
"familyName": "Kalum",
"combinedName": "Vajira Kalum"
}
],
"href": "http://something.co",
"previous": null,
"next": null,
"limit": 10,
"offset": 0,
"total": 1
},
"businessRuleResults": [],
"valid": true
}
I check if condition to validate whether response schema is correct:
if(responseBody !== null & responseBody.length >0)
{
var responseObject = JSON.parse(responseBody);
if(tv4.validate(responseObject, responseSchema))
{
// do something
}
else
{
// log some msg
}
}
Schema validation condition (nested if) get passed even when I get bellow bad response.
{
"value": {
"items": [],
"href": "http://something.co",
"previous": null,
"next": null,
"limit": 10,
"offset": 0,
"total": 0
},
"businessRuleResults": [],
"valid": true
}
Why response schema validation not failed as a response not has required fields?
When I ran your code and removed a property from the response data it seemed to work ok:
I would suggest a couple of things though - The tv4 module is not fantastic, it's not actively being worked on (for a couple of years I think) and there's a bunch of complaints/issue raised on the Postman project about how poor it is and asking for it to be replaced in the native app.
Have you considered creating a test to check the schema instead? This is very basic and could be easily refactored and wrapped in some logic but it would check the different value types of your response.
pm.test("Response data format is correct", () => {
var jsonData = pm.response.json()
// Check the type are correct
pm.expect(jsonData).to.be.an('object')
pm.expect(jsonData.value).to.be.an('object')
pm.expect(jsonData.value.items).to.be.an('array')
pm.expect(jsonData.value.items[0]).to.be.an('object')
// Check the value types are correct
pm.expect(jsonData.value.items[0].combinedName).to.be.a('string')
pm.expect(jsonData.value.items[0].givenName).to.be.a('string')
pm.expect(jsonData.value.items[0].familyName).to.be.a('string')
pm.expect(jsonData.value.items[0].patientGuid).to.a('string')
});
Also the syntax that you're using is the older style now and you don't need to JSON.parse(responseBody) the response body anymore as pm.response.json() is basically doing the same thing.
Using: MongoDB and native nodeJS mongoDB driver.
I'm trying to parse all the data from fb graph api, send it to my API and then save it to my DB.
PUT handling in my server:
//Update user's data
app.put('/api/users/:fbuser_id/:category', function(req, res) {
var body = JSON.stringify(req.body);
var rep = /"data":/;
body = body.replace(rep, '"' + req.params.category + '"' + ':');
req.body = JSON.parse(body);
db.fbusers.update({
id: req.params.fbuser_id
}, {
$set: req.body
}, {
safe: true,
multi: false
},
function(e, result) {
if (e) return next(e)
res.send((result === 1) ? {
msg: 'success'
} : {
msg: 'error'
})
});
});
I'm sending 25 elements at a time, and this code just overrides instead of updating the document.
Data I'm sending to the API:
{
"data": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Basically my API changes "data" key from sent json to the category name, f.e.:
PUT to /api/users/000/likes will change the "data" key to "likes":
{
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Then this JSON is put to the db.
Hierarchy in mongodb:
{
"_id": ObjectID("556584c8e908f0042836edce"),
"id": "0000000000000",
"email": "XXXX#gmail.com",
"first_name": "XXXXXXXX",
"gender": "male",
"last_name": "XXXXXXXXXX",
"link": "https://www.facebook.com/app_scoped_user_id/0000000000000/",
"locale": "en_US",
"name": "XXXXXXXXXX XXXXXXXXXX",
"timezone": 3,
"updated_time": "2015-05-26T18:11:59+0000",
"verified": true,
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
....and so on
}
]
}
So the problem is that my api overrides the field (in this case "likes") with newly sent data, instead of appending it to already existing data document.
I am pretty sure that I should be using other parameter than "$put" in the update, however, I have no idea which one and how to pass parameters to it programatically.
Use $push with the $each modifier to append multiple values to the array field.
var newLikes = [
{/* new item here */},
{/* new item here */},
{/* new item here */},
];
db.fbusers.update(
{ _id: req.params.fbuser_id },
{ $push: { likes: { $each: newLikes } } }
);
See also the $addToSet operator, it adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.
got this json file:
[
{
"name": "paprika",
"imgSrc": "img/paprika.jpg"
},
{
"name": "kurkku",
"imgSrc": "img/kurkku.jpg"
},
{
"name": "porkkana",
"imgSrc": "img/porkkana.jpg"
},
{
"name": "lehtisalaatti",
"imgSrc": "img/lehtisalaatti.jpg"
},
{
"name": "parsakaali",
"imgSrc": "img/parsakaali.jpg"
},
{
"name": "sipula",
"imgSrc": "img/sipuli.jpg"
},
{
"name": "peruna",
"imgSrc": "img/peruna.jpg"
},
{
"name": "soijapapu",
"imgSrc": "img/soijapapu.jpg"
},
{
"name": "pinaatti",
"imgSrc": "img/pinaatti.jpg"
}
]
Which I successfully fetch in a factory:
factory('getJson', ['$resource', function($resource) {
return $resource('json/vegs.json', {}, {
query: {method:'GET', isArray:true}
});
}]);
in my Controller I can get the json's file content:
var vegs = getJson.query();
$scope.vegs = vegs;
console.log(vegs)
console.log(typeof vegs)
The weird part is the first console.log produces an array of objects, as expected.
The second console says it's an "object", and not an array.
I can get the .json content to my view using {{vegs}}, and I can use ng-repeat as well, tho in the controller I can't do vegs[0] or vegs.length. It comes out empty.
I'm breaking my head on this for over 3 hours now :)
This isn't an 'answer'. Just an observation on one part of your issue. (Sorry, can't comment yet...new to stackoverflow).
Just a note on your comment that "The second console says it's an "object", and not an array." Using typeof on an array will always return "object".
There are various (and debated, it seems) ways to test if it's an array--Array.isArray(obj) for example.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
I am using loopjs tokeninput in a View. In this scenario I need to prePopulate the control with AdminNames for a given Distributor.
Code Follows :
$.getJSON("#Url.Action("SearchCMSAdmins")", function (data) {
var json=eval("("+data+")"); //doesnt work
var json = {
"users": [
eval("("+data+")") //need help in this part
]
}
});
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate: json.users
});
There is successful return of json values to the below function. I need the json in the below format:
var json = {
"users":
[
{ "id": "1", "name": "USER1" },
{ "id": "2", "name": "USER2" },
{ "id": "3", "name": "USER3" }
]
}