【问题标题】:How to prettyfy json with \n?如何用 \n 美化 json?
【发布时间】:2021-06-22 10:29:18
【问题描述】:

有没有办法将{"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 丢失了。

【问题讨论】:

  • stringify!=prettify。您应该将对象传递给它,而不是 JSON 文本。
  • 这有点不清楚。是否希望输出包含文字字符 \n
  • 您想要漂亮的现有 JSON 数据(即文本)还是 JavaScript 值?如果是后者,那么它是 pretty-print JSON using JavaScript 的副本
  • @SandraSchlichting 不。文档声明“就像JSON.stringify”。输出比原生方法更漂亮,是的,但仍然是相同的接口 - 您需要传递数据而不是 JSON 字符串。
  • 我仍然不太清楚您的实际输入是什么。如果是 JSON(即文本),您应该可以使用 prettier.io 来美化它。

标签: javascript node.js ecmascript-6


【解决方案1】:

哎呀,看来你需要先解析那个 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.logs 对象。但这种方法的优点是您可以在紧凑格式或普通格式之间进行选择,可以应用语法高亮,甚至可以选择要记录的对象的深度。还有更多信息herehere, 但我认为你可以使用require('util').inspect(obj, { depth: Infinity, colors: true, compact: false })

【讨论】:

    【解决方案2】:

    你试过了吗?

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

    【讨论】:

    • 我认为 OP 示例中的 \ns 是 真正的换行符,否则你是对的
    猜你喜欢
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 2011-10-04
    相关资源
    最近更新 更多