简体   繁体   中英

Find a key value in JSON object using a String in JQuery

JSON object as below. Need to find the value based on user input. The input will look like "data.location.type" , or "data.location.items[1].address.street" . Can it be done in JQuery?

{
    "data": {
        "location": {
            "type": "List",
            "count": 1,
            "items": [
                {
                    "id": 1,
                    "type": "S",
                    "address": {
                        "street": "123 Main St",
                        "city": "New York",
                        "state": "NY"
                    }
                },
                {
                    "id": 2,
                    "type": "S",
                    "address": {
                        "street": "1323 South St",
                        "city": "New York",
                        "state": "NY"
                    }
                }
            ]
        }
    }
}

First you're going to need to parse it to an object then use an object lookup function like the one below (here's a fiddle of it in action http://jsfiddle.net/C8zH2/ ):

//https://gist.github.com/megawac/6162481#file-underscore-lookup-js
var lookup = function(obj, key) {
    var type = typeof key;
    if (type == 'string' || type == "number") key = ("" + key).replace(/\[(.*?)\]/, function(m, key){//handle case where [1] may occur
        return '.' + key;
    }).split('.');
    for (var i = 0, l = key.length, currentkey; i < l; i++) {
        if (obj.hasOwnProperty(key[i])) obj = obj[key[i]];
        else return undefined;
    }
    return obj;
}

//syntax: lookup(jsonobj, input);
//Tests using your data
lookup(data, "data.location.type") //=> "List"
lookup(data, "data.location.items[1].address.street") //=> ""1323 South St"

This is just thrown together, but it should work for you...

http://jsfiddle.net/E2hEh/2/

var input = "data.location.type";
//var input = "data.location.items[1].address.street";
var parts = input.split('.');

var prev;
for(var i = 0; i < parts.length; i++){
    var index;
    if(parts[i].indexOf('[') != -1){
        var key = parts[i].substr(0, parts[i].indexOf('['));
        index = parseInt(parts[i].substr(parts[i].indexOf('[') + 1, 1), 10);
        if(!prev){
            prev = test[key][index];
        } else {
            prev = prev[key][index];
        }
    } else { 
        if(!prev){
            prev = test[parts[i]];
        } else {
            prev = prev[parts[i]];
        }

        if(i === parts.length - 1){
            alert(prev);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM