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 h
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, ' '));
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>');
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().
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
// }'