Reputation: 337
I am failing a JSON data validation test, where I am supposed to create a JSON object persons with with properties Name, EmployeeID, Experience, Company and Designation and access it using loop. I am just learning JSON and I think the problem is that it requires knowledge of nodejs too here is the json file (data.json)
'{"Name":"someName","EmployeeID":123,"Experience":123,"Company":"somecompany","Designation":"someDesignation"}'
Here is the js file:
let jsonData = require('./data.json');
let persons=JSON.parse('./data.json', jsonData);
for(i in persons){
console.log(persons.i);
}
and here is the validation file:
const Joi = require('joi');
const fss =require('fs');
const schema = Joi.object().keys({
Name: Joi.string().required(),
EmployeeID: Joi.number().required(),
Experience: Joi.number().required(),
Company: Joi.string().required(),
Designation: Joi.string().required()
});
const personSchema=Joi.object().keys({
persons:schema.required()
}).required();
var data;
try{
data = require("./data.json");
}catch(e)
{
data={};
}
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate(data, personSchema, function (err, value) {
if(err==null)
{
console.log("JSON data is valid, Status: Passed");
}else{
console.log("JSON data is invalid. Status: failed")
}
});
I am getting JSON data is invalid. Status: failed
Upvotes: 1
Views: 3141
Reputation: 6264
From the description of what you need to create, it seems you need an Array of those objects
So, the JSON should be
[{"Name":"someName","EmployeeID":123,"Experience":123,"Company":"somecompany","Designation":"someDesignation"}]
Then the "JS" would be
let persons=require('./data.json');
for(let i in persons){
console.log(persons[i]);
}
And the validator would be
const Joi = require('joi');
const fss = require('fs');
const schema = Joi.object().keys({
Name: Joi.string().required(),
EmployeeID: Joi.number().required(),
Experience: Joi.number().required(),
Company: Joi.string().required(),
Designation: Joi.string().required()
});
const personSchema = Joi.array().items(schema.required()).required();
var data;
try {
data = require("./data.json");
} catch (e) {
data = [];
}
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate(data, personSchema, function (err, value) {
if (err == null) {
console.log("JSON data is valid, Status: Passed");
} else {
console.log(err, "JSON data is invalid. Status: failed")
}
});
if the validator file should be left untouched, then the JSON needs to be as follows
{"persons":{"Name":"someName","EmployeeID":123,"Experience":123,"Company":"somecompany","Designation":"someDesignation"}}
Upvotes: 2