'How can I remove escape sequences from JSON.stringify so that it's human-readable?
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.
Solution 1:[1]
ECMAScript 2021, the 12th edition
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>');
Solution 2:[2]
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
// }'
Solution 3:[3]
JSON.stringify(value[, replacer[, space]])
Space: A String or Number object that's used to insert white space into the output JSON string for readability purposes.
Replacer: A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
So you can do
var x = {"name":"void", "type":"O'\"Rielly"};
document.write(JSON.stringify(x, null, ' '));
Solution 4:[4]
I would use JSON.stringify(),
The
JSON.stringify()method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
with four spaces and an appropriate display environment with <pre>...</pre>.
The result is good, readable, and copyable for other use.
var object = { name: 'void', type1: "O'\"This", type2: 'O\'That', a: [1, 2, 3] };
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Peter Mortensen |
| Solution 3 | void |
| Solution 4 | Peter Mortensen |
