javascript - 选择 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 作为框架来构建一个表以在同一个表中输出不同类型的数据。有什么我想念的想法吗?谢谢
解决方案
把它\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);
推荐阅读
- python - 我如何检查多列的条件并放入特定列的结果倍数
- asp.net - 如何解决错误:Asp.Net 请求中出现意外的令牌“<”?
- python - 使用 DictWriter 更改列标题
- python - 在 Django 中为生成的文件生成下载路径
- mysql - MariaDB 索引比较
- sharepoint - Azure 中的 SharePoint (VM) 使用 AAD 来宾帐户登录问题
- python - How to delete a folder and its contents on Amazon S3 using Python
- google-apps-script - how do I get the onEdit function to run
- reactjs - React Hook useEffect has missing dependencies (witout moving function inside useEffect)
- c++ - GLUT 问题:错误重新声明 C++ 内置类型“wchar_t”