我有样本json。在那个json我需要检查以下内容。
我附上了我的代码并且无法正常工作。我觉得这种做法并不好。任何人都可以向我建议正确的道路。
var test = '{ "lists": [ { "items": [ { "name": "Curd0", "sequence": 3 }, { "name": "Curd1", "sequence": 2 }, { "name": "Curd2", "sequence": 1 }, { "name": "Curd3", "sequence": 4 }, { "name": "Curd4", "sequence": 10 }, { "name": "Curd5", "sequence": 9 }, { "name": "Curd6", "sequence": 8 }, { "name": "Curd7", "sequence": 7 }, { "name": "Curd8", "sequence": 6 }, { "name": "Curd9", "sequence": 5 } ], "name": "Curd Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:18:26.169Z" }, { "items": [ { "name": "Milk0", "sequence": 3 }, { "name": "Milk1", "sequence": 2 }, { "name": "Milk2", "sequence": 1 }, { "name": "Milk3", "sequence": 4 }, { "name": "Milk4", "sequence": 10 }, { "name": "Milk5", "sequence": 9 }, { "name": "Milk6", "sequence": 8 } ], "name": "Milk Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:18:44.504Z" }, { "items": [ { "name": "Water0", "sequence": 3 }, { "name": "Water1", "sequence": 2 }, { "name": "Water2", "sequence": 1 }, { "name": "Water3", "sequence": 4 }, { "name": "Water4", "sequence": 10 }, { "name": "Water5", "sequence": 9 }, { "name": "Water6", "sequence": 8 } ], "name": "Water Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:19:02.329Z" }, { "items": [ { "name": "Fruit0", "sequence": 3 }, { "name": "Fruit1", "sequence": 2 }, { "name": "Fruit2", "sequence": 1 }, { "name": "Fruit3", "sequence": 4 } ], "name": "Fruit Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:19:15.503Z" } ] }';
function Validate(data, callback) {
for (index in lists) {
if (!lists.index.hasOwnProperty('name')) {
callback("Name cannot be empty");
}
var itemList = lists.index.items;
if (itemList.length < 5) {
callback("List need more than 5 lenth");
}
for ( i = 0; i < itemList.length; i++) {
if (!itemList[i].hasOwnProperty('name')) {
callback("Item Name cannot be empty");
}
}
}
callback(null);
}
Validate(test, function (err) {
console.log(err);
});
答案 0 :(得分:1)
every可能就是您所需要的:
function containsNameInLists(element) {
return element.hasOwnProperty('name');
}
function containsNameInItems(element) {
return element.items.every(containsKeyName);
}
function containsKeyName(element) {
return element.hasOwnProperty('name');
}
function lengthSuperiorTo5(element) {
return element.length > 5;
}
function itemsArrayLength(){
return element.items.every(lengthSuperiorTo5);
}
您可以使用JSON.parse
尝试使用字符串来测试不同的功能。
编辑:我添加了附加功能:
答案 1 :(得分:0)