Skip to content

Instantly share code, notes, and snippets.

@odeke-em
Created March 5, 2017 02:36
Show Gist options
  • Save odeke-em/1be66ae51d46763f8e0b255ddd124fa0 to your computer and use it in GitHub Desktop.
Save odeke-em/1be66ae51d46763f8e0b255ddd124fa0 to your computer and use it in GitHub Desktop.
Code to recursively parse through JSON that was extra quoted/stringified in multiple nests.
// Function to recursively parse through JSON
// that was extra quoted during stringifying for
// nested levels. This function undoes all that
// work and makes JSON objects for every object
// that it can traverse.
function recursiveJSONParse(obj) {
if (!obj)
return obj;
switch (typeof obj) {
case "string":
try {
obj = JSON.parse(obj);
} catch (ex) {
return obj;
}
break;
case "object":
break;
default:
return obj;
}
if (typeof obj !== "object")
return obj;
const nonArray = obj.length === undefined;
if (nonArray) {
var keys = Object.keys(obj);
keys.forEach(function(key) {
obj[key] = recursiveJSONParse(obj[key]);
});
} else {
for (i=0; i < obj.length; i++) {
obj[i] = recursiveJSONParse(obj[i]);
}
}
return obj;
}
function main() {
const inJSON = require("./Transloadit.json");
const util = require("util");
var obj = recursiveJSONParse(inJSON);
console.log(util.inspect(obj, {depth: 10}));
}
// If imported in a module, this part will be skipped
// otherwise when run directly e.g node <thisFile>
// that's only when main will be run.
if (process.argv.length >1 && process.argv[1] === __filename) {
main();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment