Users can download JSON files from our application, which I want to prettify for easier debugging than if all is in one line. However this increases the file size by nearly 40% even if the indentation is just a single tab or space.
As a compromise, I want to exclude all values with e.g. the key "large" from prettification, like this:
{
"small":
{
"a": 1,
"b": 2,
"large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
},
"large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
}
I tried to solve this using the replacer parameter of JSON.stringify:
JSON.stringify(data,(key,value)=>key==="large"?JSON.stringify(data):value,'\t');
However the values for the "large" keys ends up escaped:
data =
{
"small":
{
"a": 1,
"b": [2,3,4,5],
"large": {"myarray":[1,2,3,4],"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
},
"large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
}
const json = JSON.stringify(data,(key,value)=>key==="large"?JSON.stringify(data):value,'\t');
document.getElementById("json").innerText = json;
<html>
<body>
<pre id="json">
</pre>
</body>
</html>
How can I prevent this escaping from happening or otherwise partially prettify JSON in JavaScript?