Tools, FAQ, Tutorials:
JSON-stringify-Filter.html - JSON.stringify() Array Replacer
How to write a replacer array to filter values while the JSON.stringify() function is generating the JSON text string?
✍: FYIcenter.com
If you call JSON.stringify() with an array as the replacer, the array elements
will be used to filters to select object properties with keys match one of array elements.
All other object properties will be dropped.
But all array elements and standalone values will be remain in the output.
Here is a JavaScript example that a replacer array to keep only "name" and "group" properties in any objects, and filter out all other properties. But array elements are staying in the output.
<!-- JSON-stringify-Filter.html
Copyright (c) FYIcenter.com
-->
<html>
<body>
<script type="text/javascript">
var filter = ["name", "group"];
function stringifier(val) {
var str = JSON.stringify(val, ["name", "group"]);
return str;
}
document.write("<p>JSON.stringify() Replacer to Transform Values:</p>");
document.write("<pre>");
str = '{"name": "Joe", "age": 25, "group": null}';
document.write("Input = "+str+"\n");
json = stringifier(JSON.parse(str));
document.write("Output = "+json+"\n");
str = '["first", {"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("</pre>");
</script>
</body>
</html>
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":null}
Input = ["first", {"name": "Jay", "age": 55, "group": "VIP"}]
Output = ["first",{"name":"Jay","group":"VIP"}]
Input = ["name", "Kim", "age", 30, "group", "Host"]
Output = ["name","Kim","age",30,"group","Host"]
⇒ JSON-stringify-space.html - JSON.stringify() Friendly Spaced
⇐ JSON-stringify-Transformed.html - JSON.stringify() Value Transformed
2023-09-07, ∼2805🔥, 0💬
Popular Posts:
Where to find tutorials on RSS specifications? I want to learn it to describe my API services. Here ...
How to read Atom validation errors at w3.org? If your Atom feed has errors, the Atom validator at w3...
Where to find tutorials on JSON (JavaScript Object Notation) text string format? I want to know how ...
How to Install Docker Desktop 2.5.0 on Windows 10? You can follow this tutorial to Install Docker De...
Tools, FAQ, Tutorials: JSON Validator JSON-XML Converter XML-JSON Converter JSON FAQ/Tutorials Pytho...