开发者

How can I use strings in Javascript to validate data in two separate JSON dictionaries?

I need to parse data from one JSON file in order to validate arrays, keys, and values in a second JSON file. For example, I have a JSON file filled with data in this format:

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

I have a second JSON file with data like this:

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

What I need to do is take the data from the first JSON file and use it to validate data in the second JSON file. Say my "someData" JS开发者_运维百科ON looks like this:

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

How can I create a straight javascript function to determine if the "fruit" array exists in the second JSON dictionary, with a key named "type", and a value named "pear"? I guess what I'm really asking is how do I use a string from the first JSON dictionary in order to access data from the second JSON dictionary?


You can acces a property of an object either directly or if dynamically via dictionary notation (if you have its name as string):

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

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


Something like:

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

... and continuing on to check what's inside foundFruit, and so on?


The general idea is to go through array items/object properties and find matching elements.

Here is the sample that will help you accomplish that:

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


Your question intrigued me so I had a go at it in jsFiddle. I think this should work pretty well and the code is somewhat brief (sans comments). The only caveat is that it doesn't really do any type checking and could error out of "someData" wasn't an array, if "fruit" wasn't an array or if the various items in the "fruit" array weren't proper objects. But I didn't want to over complicate the code and just assumed you'll be sure the JSON format matches your example.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜