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/