【问题标题】:Select JSON unformatted code and pretty print formatted JSON into DIV选择 JSON 未格式化的代码并将格式化的 JSON 漂亮地打印到 DIV
【发布时间】:2021-08-18 08:59:49
【问题描述】:

我有一个函数,它接收一个未格式化的 JSON 代码的选择文本,我尝试使用 stringify 方法将 JSON 代码格式化为(漂亮的)视图。这是代码:

 function prettyPrintJSON(selectionInfo) {
  const unformattedJSON = selectionInfo.selectionText
  const formattedJSON = JSON.stringify(unformattedJSON, null, '\t')
}

这是未格式化的 JSON 代码:

{"colors":[{"color":"black","category":"hue","type":"primary","code":{"rgba":[255,255,255,1],"hex":"#000"}},{"color":"white","category":"value","code":{"rgba":[0,0,0,1],"hex":"#FFF"}},{"color":"red","category":"hue","type":"primary","code":{"rgba":[255,0,0,1],"hex":"#FF0"}},{"color":"blue","category":"hue","type":"primary","code":{"rgba":[0,0,255,1],"hex":"#00F"}},{"color":"yellow","category":"hue","type":"primary","code":{"rgba":[255,255,0,1],"hex":"#FF0"}},{"color":"green","category":"hue","type":"secondary","code":{"rgba":[0,255,0,1],"hex":"#0F0"}}]} 

它在表格中的外观如下:

如您所见,它没有格式化。此外,我在 google chrome 扩展程序上使用它并使用 vue.js 作为框架来构建一个表以在同一个表中输出不同类型的数据。有什么我想念的想法吗?谢谢

【问题讨论】:

  • JSON.stringify(unformattedJSON, null, '\t')中删除null and "\t",这样就变成了JSON.stringify(unformattedJSON)
  • 我刚试过这个,输出看起来还是一样。
  • 我发现,我错过了显示的
     标签。
  • 我只是想告诉你。

标签: javascript json format pretty-print


【解决方案1】:

\t变成一个数字来表示你想要多少个缩进空格

let json = {"colors":[{"color":"black","category":"hue","type":"primary","code":{"rgba":[255,255,255,1],"hex":"#000"}},{"color":"white","category":"value","code":{"rgba":[0,0,0,1],"hex":"#FFF"}},{"color":"red","category":"hue","type":"primary","code":{"rgba":[255,0,0,1],"hex":"#FF0"}},{"color":"blue","category":"hue","type":"primary","code":{"rgba":[0,0,255,1],"hex":"#00F"}},{"color":"yellow","category":"hue","type":"primary","code":{"rgba":[255,255,0,1],"hex":"#FF0"}},{"color":"green","category":"hue","type":"secondary","code":{"rgba":[0,255,0,1],"hex":"#0F0"}}]} 
 ;
 
console.log(JSON.stringify(json, null, 2)); // spacing level = 2);

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    相关资源
    最近更新 更多