【保存版】JSON.stringifyで生成したJSONを整形してdivに分かりやすく表示するテクニック
JavaScript、HTML、JSON を用いた JSON.stringify 出力を div に整形して表示する方法
JSON は、JavaScript でよく使用されるデータ形式であり、軽量で読みやすいのが特徴です。しかし、複雑な構造を持つ JSON データを扱う場合、そのまま出力するとわかりにくくなります。そこで、JSON.stringify()
関数を使って JSON データを整形して出力する方法を紹介します。
JSON.stringify()
関数は、JavaScript オブジェクトや配列を JSON 文字列に変換します。引数として、変換したいオブジェクトや配列、オプションの置換関数、インデント文字列を渡すことができます。
- 置換関数: この関数は、JSON 文字列に出力されるキーや値をカスタマイズするために使用されます。
- インデント文字列: この文字列は、JSON 文字列のインデントに使用されます。デフォルトではインデントは行われず、スペース 2 文字分のインデントを行うには
2
を渡します。
HTML で div 要素を作成
JSON データを整形して出力するには、HTML で div
要素を作成します。この要素に、JSON.stringify()
関数で生成した JSON 文字列を挿入します。
JavaScript で JSON データを取得するには、次のような方法があります。
- JavaScript オブジェクトまたは配列: すでに JavaScript オブジェクトまたは配列を持っている場合は、それを直接
JSON.stringify()
関数の引数として渡します。 - JSON ファイル: JSON ファイルからデータをを読み込むには、
XMLHttpRequest
やfetch()
API を使用します。 - サーバーからのレスポンス: サーバーからのレスポンスが JSON 形式の場合は、
JSON.parse()
関数を使用して JavaScript オブジェクトまたは配列に変換してから、JSON.stringify()
関数の引数として渡します。
例
<!DOCTYPE html>
<html>
<head>
<title>JSON.stringify output to div in pretty print way</title>
</head>
<body>
<div id="json-output"></div>
<script>
// JavaScript オブジェクトを定義
const data = {
"name": "John Doe",
"age": 30,
"address": {
"city": "New York",
"state": "NY"
},
"hobbies": ["coding", "reading", "music"]
};
// JSON 文字列を生成
const jsonString = JSON.stringify(data, null, 2);
// JSON 文字列を div 要素に出力
const jsonOutput = document.getElementById('json-output');
jsonOutput.innerHTML = jsonString;
</script>
</body>
</html>
この例では、JavaScript オブジェクトを定義し、JSON.stringify()
関数を使って整形された JSON 文字列を生成します。そして、生成された JSON 文字列を div
要素に出力します。
補足
JSON.stringify()
関数は、すべての JavaScript オブジェクトを JSON 文字列に変換できるわけではありません。例えば、関数や循環参照を含むオブジェクトは変換できません。- JSON データを整形して出力するライブラリも多数存在します。
HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>JSON.stringify Output to Div</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="json-output"></div>
<script src="script.js"></script>
</body>
</html>
CSS (style.css):
#json-output {
font-family: monospace;
white-space: pre;
padding: 10px;
border: 1px solid #ccc;
}
JavaScript (script.js):
// JavaScript object to be formatted
const data = {
"name": "John Doe",
"age": 30,
"address": {
"city": "New York",
"state": "NY"
},
"hobbies": ["coding", "reading", "music"]
};
// Convert the object to a pretty-printed JSON string
const jsonString = JSON.stringify(data, null, 2);
// Get the div element to display the JSON output
const jsonOutput = document.getElementById('json-output');
// Set the div's innerHTML to the JSON string
jsonOutput.innerHTML = jsonString;
Explanation:
- Creates a
div
element with the IDjson-output
to hold the formatted JSON output. - Links the
style.css
file for styling the output. - Includes the
script.js
file to handle the JSON formatting and display.
- Creates a
- Sets the font family for the
json-output
div to a monospace font for better readability. - Enables preformatted text (
white-space: pre
) to preserve the indentation and spacing of the JSON output. - Adds padding and a border for visual separation.
- Sets the font family for the
- Defines a JavaScript object
data
containing the JSON data to be formatted. - Uses
JSON.stringify(data, null, 2)
to convert the object to a pretty-printed JSON string. Thenull
argument indicates no custom replacement function, and2
specifies two spaces for indentation. - Retrieves the
json-output
div element usingdocument.getElementById()
. - Sets the
innerHTML
property of the div to thejsonString
, effectively displaying the formatted JSON output within the div element.
- Defines a JavaScript object
This code demonstrates how to create a simple HTML page, style the output, and use JavaScript to convert a JSON object to a formatted string and display it neatly within a designated div element.
Method 1: Using a JSON library
Example:
<!DOCTYPE html>
<html>
<head>
<title>JSON.stringify Output to Div</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/jsonformatter.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jsonformatter.min.js"></script>
</head>
<body>
<div id="json-output"></div>
<script>
// JavaScript object to be formatted
const data = {
"name": "John Doe",
"age": 30,
"address": {
"city": "New York",
"state": "NY"
},
"hobbies": ["coding", "reading", "music"]
};
// Create a JSONFormatter instance
const formatter = new JSONFormatter(data, {
indent: 2, // Set indentation level
theme: 'dark' // Set theme (optional)
});
// Render the formatted JSON to the div
const jsonOutput = document.getElementById('json-output');
jsonOutput.innerHTML = formatter.render();
</script>
</body>
</html>
Method 2: Manual string manipulation
For more control over the formatting, you can manually manipulate the JSON string produced by JSON.stringify()
. This approach involves replacing newlines, spaces, and other characters to achieve the desired indentation and styling.
// JavaScript object to be formatted
const data = {
"name": "John Doe",
"age": 30,
"address": {
"city": "New York",
"state": "NY"
},
"hobbies": ["coding", "reading", "music"]
};
// Convert the object to a JSON string
const jsonString = JSON.stringify(data);
// Replace newlines with `<br>` tags
const formattedString = jsonString.replace('\n', '<br>');
// Replace spaces with indentation
const indentedString = formattedString.replace(/ /g, ' ');
// Get the div element to display the JSON output
const jsonOutput = document.getElementById('json-output');
// Set the div's innerHTML to the formatted JSON string
jsonOutput.innerHTML = indentedString;
This method provides more flexibility in customizing the formatting but requires more manual string manipulation.
javascript html json