如何在Javascript中使用字符串来验证两个单独的JSON字典中的数据?

时间:2011-06-03 22:09:53

标签: javascript string json

我需要解析来自一个JSON文件的数据,以便在第二个JSON文件中验证数组,键和值。例如,我有一个JSON文件,其中填充了以下格式的数据:

{ "someData":["array", "key", "value"] }

我有第二个JSON文件,其数据如下:

{ "fruit": [ {"type":"apple"}, 
             {"type":"cherry"},
             {"type":"pear"} ] }

我需要做的是从第一个JSON文件中获取数据并使用它来验证第二个JSON文件中的数据。说我的“someData”JSON看起来像这样:

{ "someData":["fruit", "type", "pear"] }

如何创建一个直接的javascript函数来确定第二个JSON字典中是否存在“fruit”数组,其中一个名为“type”的键和一个名为“pear”的值?我想我真正问的是如何使用第一个JSON字典中的字符串来访问第二个JSON字典中的数据?

4 个答案:

答案 0 :(得分:0)

您可以直接访问对象的属性,也可以通过字典表示法动态访问对象的属性(如果您的名称为字符串):

var j2 = { "fruit": [ {"type":"apple"}, 
             {"type":"cherry"},
             {"type":"pear"} ] };

j2.fruit[0].type = j2["fruit"][0]["type"] = "apple"

答案 1 :(得分:0)

类似的东西:

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);

......继续检查findFruit里面的内容,等等?

答案 2 :(得分:0)

一般的想法是遍历数组项/对象属性并找到匹配的元素。

以下示例将帮助您实现这一目标:

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));

答案 3 :(得分:0)

你的问题引起了我的兴趣,所以我在jsFiddle中找到了它。我认为这应该工作得很好,代码有点简短(没有评论)。唯一需要注意的是,它并没有真正进行任何类型检查,并且如果“fruit”不是数组,或者“fruit”数组中的各个项目不是“数据”,那么“someData”的错误就不是数组适当的对象。但我不想让代码复杂化,只是假设您确定JSON格式与您的示例匹配。

http://jsfiddle.net/nG7BZ/

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;
}