我无法通过JSON数据验证测试,在该测试中,我应该创建具有属性Name,EmployeeID,Experience,Company和Designation的JSON对象 persons ,并使用循环进行访问。 我只是在学习JSON,我认为问题在于它也需要nodejs的知识。 这是json文件(data.json)
'{"Name":"someName","EmployeeID":123,"Experience":123,"Company":"somecompany","Designation":"someDesignation"}'
这是js文件:
let jsonData = require('./data.json');
let persons=JSON.parse('./data.json', jsonData);
for(i in persons){
console.log(persons.i);
}
这是验证文件:
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")
}
});
我收到 JSON数据无效。状态:失败
答案 0 :(得分:1)
从对您需要创建的内容的描述来看,似乎您需要这些对象的数组
因此,JSON应该是
[{"Name":"someName","EmployeeID":123,"Experience":123,"Company":"somecompany","Designation":"someDesignation"}]
那么“ JS”就是
let persons=require('./data.json');
for(let i in persons){
console.log(persons[i]);
}
验证者将是
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")
}
});
如果验证器文件保持不变,则JSON必须如下所示
{"persons":{"Name":"someName","EmployeeID":123,"Experience":123,"Company":"somecompany","Designation":"someDesignation"}}