Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  134] [ 3]  / answers: 1 / hits: 45172  / 9 Years ago, thu, january 7, 2016, 12:00:00

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.


More From » json

 Answers
22

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(/[^ws]/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().


[#63815] Monday, January 4, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseb

Total Points: 252
Total Questions: 96
Total Answers: 106

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
analiseb questions
;