在 JavaScript 中美化文本区域输入中的 JSON 数据?

javascriptweb developmentobject oriented programming更新于 2025/11/17 23:40:17

为此,请使用 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.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/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 编辑器中使用实时服务器打开选项。

输出

将产生以下输出 −

现在,我要输入一些不好的(未格式化的)JSON。示例 JSON 数据如下 −

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


相关文章


有用资源