首页 > 解决方案 > 选择 JSON 未格式化的代码并将格式化的 JSON 漂亮地打印到 DIV

问题描述

我有一个函数,它接收一个未格式化的 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 作为框架来构建一个表以在同一个表中输出不同类型的数据。有什么我想念的想法吗?谢谢

标签: javascriptjsonformatpretty-print

解决方案


把它\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);


推荐阅读