0

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"
                    }
                }
            ]
        }
    }
}
4

2 回答 2

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"
于 2013-10-17T21:05:15.283 回答
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);
        }
    }
}
于 2013-10-17T21:32:57.657 回答