【问题标题】:Format the pretty JSON object格式化漂亮的 JSON 对象
【发布时间】:2017-03-14 15:02:45
【问题描述】:

我正在使用 Node.js 来漂亮地打印 JSON 对象。 这一行

obj = JSON.stringify(obj, null, 1); 

结果:

 {
  "name": "Member",
  "type": "object",
  "properties": {
   "Id": {
    "type": "GUID",
    "description": "Unique identifier"
   },
   "Name": {
    "type": "string",
    "description": "Members name"
   }
  }
 }

但我希望它看起来像这样:

 {
  "name": "Member",
  "type": "object",
  "properties": {
   "Id": {"type": "GUID", "description": "Unique identifier"},
   "Name": {"type": "string", "description": "Members name"}
  }     
 }

我该怎么做?

【问题讨论】:

  • 不是标准的JSON.stringify,如果你幸运的话,你要么必须手动完成,要么用谷歌搜索其他曾经做过的人(尽管你必须跟踪层次结构深度等等将换行符折叠成空格,所以绝对不是微不足道的)。

标签: json node.js pretty-print


【解决方案1】:

使用 JSON.stringify,然后对结果字符串使用一些正则表达式。
首先去掉顶层大括号,然后用空白替换 {...} 组中的每个换行符。

【讨论】:

  • 我想过这样做。我希望有一种更简单的方法:)
  • 这很困难,因为您只希望同一行的底层子级
猜你喜欢
  • 2016-01-09
  • 1970-01-01
  • 2021-09-19
  • 2019-06-07
  • 2017-12-28
  • 1970-01-01
  • 2017-05-05
  • 2013-09-23
  • 2020-06-14
相关资源
最近更新 更多