javascript - 使用 JQuery 中的字符串查找 JSON 对象中的键值

标签 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"
                    }
                }
            ]
        }
    }
}

最佳答案

首先,您需要将其解析为一个对象,然后使用如下所示的对象查找函数(这是一个实际操作的 fiddle 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"

关于javascript - 使用 JQuery 中的字符串查找 JSON 对象中的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19437205/

相关文章:

javascript - 是否可以访问 VoiceXML 文档的 DOM?如何?

javascript - 使用溢出时隐藏滚动条 :scroll; but keep scrolling ability

javascript - jQuery - 事件无法正常工作

iphone - 在 iphone 中使用 Brautaset Json 框架时出错

javascript - Ajax JSON异常意外的 token [

javascript - 是否有一个 bool 函数来知道选择多个是否选择了多个选项?

javascript - 将 Canvas 图像作为文件流 HTML5 发送

javascript - jquery 对话框 - 替换对话框元素

json - Moshi 用不同的键解析 json

javascript - 如何在IE中实现 "Rounded Corner on hover effect"?