Tools, FAQ, Tutorials:
JSON-stringify-Transformed.html - JSON.stringify() Value Transformed
How to write a replacer function to transform values while the JSON.stringify() function is generating the JSON text string?
✍: FYIcenter.com
Below is a good example on using a replacer function with the JSON.stringify() call
to transform output values:
<!-- JSON-stringify-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 stringifier(val) {
var str = JSON.stringify(val,transformer);
return str;
}
document.write("JSON.stringify() Replacer to Transform Values:
");
document.write("");
str = '{"name": "Joe", "age": 25, "group": null}';
document.write("Input = "+str+"\n");
json = stringifier(JSON.parse(str));
document.write("Output = "+json+"\n");
str = '{"name": "Jay", "age": 55, "group": "VIP"}';
document.write("Input = "+str+"\n");
json = stringifier(JSON.parse(str));
document.write("Output = "+json+"\n");
str = '{"name": "Kim", "age": 30, "group": "Host"}';
document.write("Input = "+str+"\n");
json = stringifier(JSON.parse(str));
document.write("Output = "+json+"\n");
document.write("");
</script>
</body>
</html>
The transformer() is used as the replacer function in the JSON.stringify() call to remove the "age" property, and to provide a default value "Guest" to the "group" property.
Open the above code in a Web browser. You see the following output:
JSON.stringify() Replacer to Transform Values:
Input = {"name": "Joe", "age": 25, "group": null}
Output = {"name":"Joe","group":"Guest"}
Input = {"name": "Jay", "age": 55, "group": "VIP"}
Output = {"name":"Jay","group":"VIP"}
Input = {"name": "Kim", "age": 30, "group": "Host"}
Output = {"name":"Kim","group":"Host"}
⇒ JSON-stringify-Filter.html - JSON.stringify() Array Replacer
2023-09-07, ∼1672🔥, 0💬
Popular Posts:
How To Use an Array as a Queue in PHP? A queue is a simple data structure that manages data elements...
How to use the "set-body" Policy Statement for an Azure API service operation? The "set-body" Policy...
How to use the "find-and-replace" Policy Statement for an Azure API service operation? The "find-and...
Can Two Forms Be Nested? Can two forms be nested? The answer is no and yes: No. You can not nest two...
How to dump (or encode, serialize) a Python object into a JSON string using json.dumps()? The json.d...