![](/img/trans.png)
[英]How do I use if, else if and else statements to validate two strings
[英]How can I use strings in Javascript to validate data in two separate JSON dictionaries?
我需要解析來自一個 JSON 文件的數據,以驗證第二個 JSON 文件中的 arrays、鍵和值。 例如,我有一個 JSON 文件,其中填充了以下格式的數據:
{ "someData":["array", "key", "value"] }
我有第二個 JSON 文件,其中包含如下數據:
{ "fruit": [ {"type":"apple"},
{"type":"cherry"},
{"type":"pear"} ] }
我需要做的是從第一個 JSON 文件中獲取數據,並使用它來驗證第二個 JSON 文件中的數據。 說我的“someData” JSON 看起來像這樣:
{ "someData":["fruit", "type", "pear"] }
如何創建一個直接的 javascript function 以確定“fruit”數組是否存在於第二個 JSON 字典中,鍵名為“type”,值名為“p”? 我想我真正要問的是如何使用第一個 JSON 字典中的字符串來訪問第二個 JSON 字典中的數據?
您可以直接訪問 object 的屬性,也可以通過字典表示法動態訪問(如果您將其名稱作為字符串):
var j2 = { "fruit": [ {"type":"apple"},
{"type":"cherry"},
{"type":"pear"} ] };
j2.fruit[0].type = j2["fruit"][0]["type"] = "apple"
就像是:
function isArray(o)
{
if((typeof o) != 'object')
return false;
if(o.length == undefined)
return false;
return true;
}
var first;
var second;
// read them...
var foundFruit = second[first["someData"][0]];
var aok = isArray(foundFruit);
...並繼續檢查 foundFruit 里面有什么,等等?
大體思路是通過數組項/對象屬性來go並找到匹配的元素。
以下示例將幫助您完成此操作:
function validate(data, query){
var currentData = data;
var counter = 0;
var foundMatch = false;
while (counter < query.length){
foundMatch = false;
if (currentData instanceof Array){
// 1. key points to an array
if (counter < query.length){
var key = query[counter];
var i;
for (i = 0; i < currentData.length; i++){
var item = currentData[i];
if (counter === query.length - 1){
foundMatch = item === query[counter];
if (foundMatch){
counter++;
break;
}
} else if (item.hasOwnProperty(key)){
if (counter < query.length - 2){
currentData = item[key];
foundMatch = true;
counter++;
} else {
foundMatch = item[key] === query[counter + 1];
if (foundMatch){
counter += 2;
break;
}
}
}
if (foundMatch) {
break;
}
}
} else {
foundMatch = false;
break;
}
} else if (counter === query.length - 1){
// 2. key points to the last item
foundMatch = currentData === query[counter];
counter++;
} else {
if (currentData.hasOwnProperty(query[counter])){
// 3. key points to an object
currentData = currentData[query[counter]];
foundMatch = true;
counter++;
}
}
if (!foundMatch){
break;
}
}
return foundMatch;
}
var query = ["fruit", "type", "pear"];
var data = {"fruit": [{"type":"apple"}, {"type":"cherry"}, {"type":"pear"} ] };
// some other test data
//var query = ["fruit", "val", "anotherArray", 42];
//var data = {"fruit": [{"type":"apple"}, {"val":{anotherArray:[1,2,42]}}, {"type":"pear"} ] };
console.log(validate(data, query));
你的問題引起了我的興趣,所以我在 jsFiddle 中有一個 go。 我認為這應該工作得很好,並且代碼有點簡短(沒有評論)。 唯一需要注意的是,如果“fruit”不是數組或者“fruit”數組中的各個項目不是,它可能不會真正進行任何類型檢查,並且可能會從“someData”不是數組中出錯t 適當的對象。 但我不想使代碼過於復雜,只是假設您會確定 JSON 格式與您的示例匹配。
var checkFor = {
"someData": ["fruit", "type", "pear"],
"someMoreData": ["fruit", "color", "organge"],
"evenMoreData": ["vegetable", "type", "spinach"],
"lastBitOfData": ["vegetable", "color", "green"]
};
var checkIn = {
"fruit": [
{"type": "apple", "color": "red"},
{"type": "cherry", "color": "red"},
{"type": "pear", "color": "green"}],
"vegetable": [
{"type": "broccoli", "color": "green"},
{"type": "tomato", "color": "red"},]
};
// Loop through all the keys in checkFor and see they exist in checkIn
for(var name in checkFor) {
/*
Keys ( will be "someData, someMoreData, evenMoreData, etc" in no particular order
Grab each key (name) of checkFor and assign it to a variable (arr)
Assign indexes 0, 1, 2 of arr to parentKey, key, value - respectively
*/
var arr = checkFor[name], parentKey = arr[0], key = arr[1], value = arr[2];
// Check to see if for
var exists = forExistsIn(checkIn, parentKey, key, value);
// Write out our result
document.write(name+ " (" + arr + ") exists in checkIn => " + exists + "<br>");
}
/*
Checks for the parentKey in obj and then checks
to make sure obj[parentKey] contains at least 1 sub object whose
"key" === "value"
*/
function forExistsIn(obj, parentKey, key, value) {
return typeof obj[parentKey] !== "undefined" &&
obj[parentKey].filter(function(item) {
return item[key] === value;
}).length > 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.