This is an example program that shows how to use the stringify() and parse() functions as inverses for JSON in JavaScript.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>XoaX.net's Javascript</title> <!-- Supply a transparent 1x1 favicon --> <link rel="icon" href="data:,"> <script type="text/javascript" src="StringifyParseInverse.js"></script> </head> <body onload="Initialize()"> <h1>Original Object</h1> <pre id="idObject1"></pre> <h1>Stringify Result</h1> <pre id="idObject2"></pre> <h1>Parsed Stringified Result</h1> <pre id="idObject3"></pre> </body> </html>
function Initialize() {
let qObject = {
msName: "Jesus Christ",
mqBirthday: new Date("0000-12-25"),
mdAge: 30.5,
mbIsGod: new Boolean(1),
mbIsMan: true,
mqBiologicalFather: null,
msaApostles: ["Peter", "John", "James", "Thomas"],
mfnMultiply: function(x) { return 100000*x;},
mqParents: {sFather: "Joseph", sMother: "Mary"}
};
document.getElementById("idObject1").innerHTML = PrintAnObject("qObject", qObject);
// This second parameter needs to convert functions to strings. Otherwise, functions will be skipped.
// The third parameter '\t' is a spacing string or number. With tab, it just sets the indentation.
let sJson = JSON.stringify(qObject, (key, value) => {
if (typeof value === "function") {
// Convert the function code to a string
return value.toString();
}
return value;
}, '\t');
document.getElementById("idObject2").innerHTML = sJson;
localStorage.setItem("StoredJSON", sJson);
let sRetrieved = localStorage.getItem("StoredJSON");
let qParsedObject = JSON.parse(sRetrieved, function (sKey, qValue) {
// Functions and dates must be handled this way. Otherwise, they become strings.
if (sKey === "mfnMultiply") {
return eval("("+qValue+")");
} else if (sKey === "mqBirthday") {
return new Date(qValue);
} else {
return qValue;
}
});
document.getElementById("idObject3").innerHTML = PrintAnObject("qParsedObject", qParsedObject);
}
function PrintAnObject(sName, qObject, sPre = "") {
let sOutput = typeof(qObject) + ": " + sName + " = " + qObject + '<br />';
for (let sProperty in qObject) {
if (typeof(qObject[sProperty]) == "object") {
sOutput += PrintAnObject(sProperty, qObject[sProperty], sPre + " ");
} else {
sOutput += sPre+" "+typeof(qObject[sProperty])+': '+sProperty+' = '+qObject[sProperty]+'<br />';
}
}
return sPre + sOutput;
}© 20072026 XoaX.net LLC. All rights reserved.