我用這個,
function jsonPathToValue(jsonData, path) {
if (!(jsonData instanceof Object) || typeof (path) === "undefined") {
throw "InvalidArgumentException(jsonData:" + jsonData + ", path:" + path);
}
path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
path = path.replace(/^\./, ''); // strip a leading dot
var pathArray = path.split('.');
for (var i = 0, n = pathArray.length; i < n; ++i) {
var key = pathArray[i];
if (key in jsonData) {
if (jsonData[key] !== null) {
jsonData = jsonData[key];
} else {
return null;
}
} else {
return key;
}
}
return jsonData;
}
測試,
json = {"a1":{"a2":{"a3":"value"}}};
console.log(jsonPathToValue(json, "a1.a2.a3")); //=> shows: value
從here啓發。
這個答案很糟糕... –