Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
INB Avatar asked Jan 07 '16 06:01

INB


People also ask

How remove all escape characters from JSON string?

String jsonFormattedString = jsonStr. replaceAll("\\", "");

Does JSON Stringify escape quotes?

stringify escapes double quotes every time when stringified.

Does JSON Stringify remove spaces?

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.

What is reverse of JSON Stringify?

JSON. parse is the opposite of JSON. stringify .


3 Answers

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>');
like image 107
Adib Zaini Avatar answered Oct 23 '22 18:10

Adib Zaini


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
// }'
like image 32
gurvinder372 Avatar answered Oct 23 '22 17:10

gurvinder372


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().

like image 43
Pradeep Potnuru Avatar answered Oct 23 '22 16:10

Pradeep Potnuru