使用JQuery中的String在JSON对象中查找键值

时间:2013-10-17 21:01:28

标签: javascript jquery json

JSON对象如下。需要根据用户输入找到值。输入看起来像"data.location.type""data.location.items[1].address.street"。可以在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"
                    }
                }
            ]
        }
    }
}

2 个答案:

答案 0 :(得分:2)

首先你需要将它解析为一个对象,然后使用一个像下面那样的对象查找函数(这里是它的一个小动作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"

答案 1 :(得分:1)

这只是一起抛出,但它应该对你有用......

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