如何用预处理json


有没有办法把{"query":{"match_all" : {} }}变成{n "query":{n "match_all" : {}n }n}

我试过

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);

哪里有

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

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

由于某种原因,n的丢失了。

Whoops,看起来您需要首先解析JSON。

试试这个:

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);

您可以改用JSON.stringify–只需将第三个参数设置为number(缩进那么多空格(或string(缩进那个字符串(。

现在只需将第二个参数设置为null

示例:

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);


如果您只是在调试,另一个选项是使用require('util').inspect(obj)console.log是对象。但这种方法的优点是,您可以在紧凑格式或普通格式之间进行选择,您可以应用语法高亮显示,甚至可以选择要记录的对象的深度。这里和这里有更多信息,但我认为你可以使用require('util').inspect(obj, { depth: Infinity, colors: true, compact: false })

你试过这个吗?

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'))

最新更新