为了账号安全,请及时绑定邮箱和手机立即绑定

JSON 数据验证失败

JSON 数据验证失败

Helenr 2021-11-18 16:29:55
我没有通过 JSON 数据验证测试,我应该在其中创建一个具有名称、员工 ID、经验、公司和名称属性的 JSON 对象人员,并使用循环访问它。我只是在学习 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 数据无效。状态:失败
查看完整描述

1 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

根据您需要创建的内容的描述,您似乎需要这些对象的 Array


所以,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"}}


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 239 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信