从@Alnitak answer开始,我构建了这个源代码,它下载了一个实际的.JSON文件并对其进行处理,为每一步打印到控制台解释字符串,以及在传递错误键的情况下的更多细节:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script>
function retrieveURL(url) {
var client = new XMLHttpRequest();
prefix = "https://cors-anywhere.herokuapp.com/"
client.open('GET', prefix + url);
client.responseType = 'text';
client.onload = function() {
response = client.response; // Load remote response.
console.log("Response received.");
parsedJSON = JSON.parse(response);
console.log(parsedJSON);
console.log(JSONitemByPath(parsedJSON,"geometry[6].obs[3].latituade"));
return response;
};
try {
client.send();
} catch(e) {
console.log("NETWORK ERROR!");
console.log(e);
}
}
function JSONitemByPath(o, s) {
structure = "";
originalString = s;
console.log("Received string: ", s);
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
console.log("Converted to : ", s);
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
console.log("Single keys to parse: ",a);
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
console.log("object." + structure + a[i], o);
structure += a[i] + ".";
} else {
console.log("ERROR: wrong path passed: ", originalString);
console.log(" Last working level: ", structure.substr(0,structure.length-1));
console.log(" Contents: ", o);
console.log(" Available/passed key: ");
Object.keys(o).forEach((prop)=> console.log(" "+prop +"/" + k));
return;
}
}
return o;
}
function main() {
rawJSON = retrieveURL("http://haya2now.jp/data/data.json");
}
</script>
</head>
<body onload="main()">
</body>
</html>
输出的例子:
Response received.
json-querier.html:17 {geometry: Array(7), error: Array(0), status: {…}}
json-querier.html:34 Received string: geometry[6].obs[3].latituade
json-querier.html:36 Converted to : geometry.6.obs.3.latituade
json-querier.html:40 Single keys to parse: (5) ["geometry", "6", "obs", "3", "latituade"]
json-querier.html:46 object.geometry (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
json-querier.html:46 object.geometry.6 {hayabusa2: {…}, earth: {…}, obs: Array(6), TT: 2458816.04973593, ryugu: {…}, …}
json-querier.html:46 object.geometry.6.obs (6) [{…}, {…}, {…}, {…}, {…}, {…}]
json-querier.html:46 object.geometry.6.obs.3 {longitude: 148.98, hayabusa2: {…}, sun: {…}, name: "DSS-43", latitude: -35.4, …}
json-querier.html:49 ERROR: wrong path passed: geometry[6].obs[3].latituade
json-querier.html:50 Last working level: geometry.6.obs.3
json-querier.html:51 Contents: {longitude: 148.98, hayabusa2: {…}, sun: {…}, name: "DSS-43", latitude: -35.4, …}
json-querier.html:52 Available/passed key:
json-querier.html:53 longitude/latituade
json-querier.html:53 hayabusa2/latituade
json-querier.html:53 sun/latituade
json-querier.html:53 name/latituade
json-querier.html:53 latitude/latituade
json-querier.html:53 altitude/latituade
json-querier.html:18 undefined