Tools, FAQ, Tutorials:
JSON-parse-Transformed.html - JSON.parse() Value Transformed
How to write a reviver function to transform values while the JSON.parse() function is parsing the JSON text string?
✍: FYIcenter.com
Below is a good example on using a reviver function with the JSON.parse() call
to transform parsed JSON element values:
<!-- JSON-parse-Transformed.html
Copyright (c) FYIcenter.com
-->
<html>
<body>
<script type="text/javascript">
function transformer(key, value) {
if (key == "age") {
return undefined;
} else if (key == "group" && value==null) {
return "Guest";
} else {
return value;
}
}
function parser(str) {
document.write("\njson = "+str+"\n");
var obj = JSON.parse(str,transformer);
for (var prop in obj) {
document.write(`obj.${prop} = ${obj[prop]}\n`);
}
}
document.write("<p>JSON.parse() Reviver to Transform Values:</p>");
document.write("<pre>");
parser('{"name": "Joe", "age": 25, "group": null}');
parser('{"name": "Jay", "age": 55, "group": "VIP"}');
parser('{"name": "Kim", "age": 30, "group": "Host"}');
document.write("</pre>");
</script>
</body>
</html>
The transformer() is used as the reviver function in the JSON.parse() call to remove the "age" name value pairs, and to provide a default value "Guest" to the "group" name value pairs.
Open the above code in a Web browser. You see the following output:
JSON.parse() Reviver to Transform Values:
json = {"name": "Joe", "age": 25, "group": null}
obj.name = Joe
obj.group = Guest
json = {"name": "Jay", "age": 55, "group": "VIP"}
obj.name = Jay
obj.group = VIP
json = {"name": "Kim", "age": 30, "group": "Host"}
obj.name = Kim
obj.group = Host
⇒ JSON.stringify() Function in JavaScript
2017-09-08, ∼3073🔥, 0💬
Popular Posts:
How to extend json.JSONEncoder class? I want to encode other Python data types to JSON. If you encod...
How to use urllib.parse.urlencode() function to encode HTTP POST data? My form data has special char...
How to build a test service operation to dump everything from the "context.Request" object in the re...
What's Wrong with "while ($c=fgetc($f)) {}" in PHP? If you are using "while ($c=fgetc($f)) {}" to lo...
How to use the "Ctrl-p Ctrl-q" sequence to detach console from the TTY terminal of container's runni...