在 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.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 編輯器中選擇使用 live server 開啟選項。
輸出
這將產生以下輸出 −

現在,我將放入一些不良(未格式化)JSON。示例 JSON 資料如下 −

單擊按鈕後,您將獲得以下示例輸出,即正確格式化的 JSON −

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP