This is an example program that shows how to parse data types with a reviver function in a JSON string 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="ParseJsonUsingReviver.js"></script> </head> <body onload="Initialize()"> <span id="idObject"></span> </body> </html>
function Initialize() {
const sJsonText = '{ "Products": [ {"Name":"Apple", "Price":1.25}, {"Name":"Pear", "Price":0.98}, {"Name":"Banana", "Price":0.73} ] }';
// The second argument is the reviver function and it is called on each key-value pair.
const qJsonObject = JSON.parse(sJsonText, function (sKey, qValue) {
if (sKey == "Price") {
// Give a 10% discount on the prices
return qValue*.9;
} else {
return qValue;
}
});
document.getElementById("idObject").innerHTML = PrintAnObject("qJsonObject", qJsonObject, sPre = "");
}
function PrintAnObject(sName, qObject, sPre = "") {
let sOutput = typeof(qObject) + " " + qObject.constructor.name + ": " + sName + '<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.