When I call JSON.stringify() on a complex object in JavaScript, it produces a string with lots of escape sequences (\", \\", etc.).
How can I make it create a human-readable JSON string instead? I.e., one that you can copy/paste into one of the many JSON validators on the web?
To clarify, my #1 concern is removing the escape sequences.
String jsonFormattedString = jsonStr. replaceAll("\\", "");
stringify escapes double quotes every time when stringified.
Calling JSON. stringify(data) returns a JSON string of the given data. This JSON string doesn't include any spaces or line breaks by default.
JSON. parse is the opposite of JSON. stringify .
You can use
JSON.stringify()
and replaceAll()
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
const foo = {
A: 'This is my \\',
B: 'This \\ is his \\'
};
let jsonString = JSON.stringify(foo, null, 2);
document.write(jsonString);
jsonString = jsonString.replaceAll('\\', '');
document.write('<pre>' + jsonString + '</pre>');
You can use formatting on JSON.stringify.
'\t'
represent a tab character
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
// "uno": 1,
// "dos": 2
// }'
You can use the replacer. The second parameter provided by JSON.stringify.Replacer could be a function or array.
In your case we can create a function which replaces all the special characters with a blank space.The below example replaces the whitespaces and underscores.
function replacer(key, value) {
return value.replace(/[^\w\s]/gi, '');
}
var foo = {"a":"1","b":2};
var jsonString = JSON.stringify(foo, replacer);
If you simply want to replace the one special character, use:
JSON.stringify({ a: 1, b: 2 }, null, '\t');
For more information on replacer, check the MDN page JSON.stringify().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With