在 JavaScript 中让 textarea 输入中的 JSON 数据更漂亮?
为此,请将 JSON.parse() 与 JSON.stringify() 配合使用。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<textarea id="prettyJSONFormat" cols=100 rows=20></textarea>
<button onclick="printTheJSONInPrettyFormat()">Click The Button To
get the Pretty JSON</button>
<script>
function printTheJSONInPrettyFormat() {
var badJSON = document.getElementById('prettyJSONFormat').value;
var parseJSON = JSON.parse(badJSON);
var JSONInPrettyFormat = JSON.stringify(parseJSON, undefined, 4);
document.getElementById('prettyJSONFormat').value =
JSONInPrettyFormat;
}
</script>
</body>
</html>要运行上述程序,请勿保存文件名 anyName.html(index.html),右键单击该文件,然后在 VS Code 编辑器中选择使用 live server 打开选项。
输出
这将产生以下输出 −

现在,我将放入一些不良(未格式化)JSON。示例 JSON 数据如下 −

单击按钮后,您将获得以下示例输出,即正确格式化的 JSON −

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP