How to prettyfy json with \n?

Viewed 156

Is there a way to turn {"query":{"match_all" : {} }} into {\n "query":{\n "match_all" : {}\n }\n}?

I have tried with

const stringify = require("json-stringify-pretty-compact");

const a = '{\n  "query":{\n    "match_all" : {}\n  }\n}';
const b = '{"query":{"match_all" : {} }}';
console.log(a);
console.log(b);
const c = stringify(b);
console.log(c);

where I get

{
  "query":{
    "match_all" : {}
  }
}


{"query":{"match_all" : {} }}
"{\"query\":{\"match_all\" : {} }}"

For some reason the \n's are missing.

2 Answers

Whoops, it looks like you need to parse that JSON first.

Try this:

const stringify = require("json-stringify-pretty-compact");

const a = '{\n  "query":{\n    "match_all" : {}\n  }\n}';
const b = '{"query":{"match_all" : {} }}';
console.log(a);
console.log(b);
const c = stringify(JSON.parse(b));
console.log(c);

You can use JSON.stringify instead – Just set the third argument to a number (to indent by that many spaces) or a string (to indent by that string).

Just set the second argument to null for now

Example:

const a = '{\n  "query":{\n    "match_all" : {}\n  }\n}';
const b = '{"query":{"match_all":{}}}';
console.log(a);
console.log(b);
const c = JSON.stringify(JSON.parse(b), null, 4);
console.log(c);


Another option, if you are just debugging, would be to use require('util').inspect(obj), which console.logs the object. But the advantage of this method is that you can choose between a compact format or the normal format, you can apply syntax highlighting, and you can even choose the depth of the object to be logged. There's more info here and here, but I think you could use require('util').inspect(obj, { depth: Infinity, colors: true, compact: false })

Have you tried this ?

JSON.stringify(b, null, 2) // 2 for 2 whitespace indent
.replace(/\n/g, '\\n') // To display \n rather than an actual line return

const obj = {"query":{"match_all" : {} }}

console.log(JSON.stringify(obj, null,2).replace(/\n/g, '\\n'))

Related