【保存版】JSON.stringifyで生成したJSONを整形してdivに分かりやすく表示するテクニック

2024-06-21

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 ファイルからデータをを読み込むには、XMLHttpRequestfetch() 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 ID json-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.
    • 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.
    • 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. The null argument indicates no custom replacement function, and 2 specifies two spaces for indentation.
    • Retrieves the json-output div element using document.getElementById().
    • Sets the innerHTML property of the div to the jsonString, effectively displaying the formatted JSON output within the div element.

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, '&nbsp;');

// 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


crypto.randomUUID() を使ってUUIDを生成する

JavaScriptでGUID/UUIDを生成するには、いくつかの方法があります。crypto. randomUUID()を使うNode. js 14. 17. 0以降と一部のブラウザでは、crypto. randomUUID()というAPIを使用して、ランダムなUUIDを生成できます。このAPIは、最もシンプルで安全な方法の一つです。...


jQuery.Ajax vs その他の方法:ファイルをダウンロードする最適な方法は?

xhrFields オプションを使用するxhrFields オプションを使用して、responseType プロパティを blob に設定します。 これにより、サーバーからの応答がバイナリデータとして取得されます。Blob オブジェクトからファイルを作成する...


Node.jsでフォルダを再帰的にコピーする:ベストプラクティスとトラブルシューティング

fs モジュールとコールバックを使用するNode. js の標準モジュールである fs を使用して、フォルダーを再帰的にコピーすることができます。ただし、この方法は非同期処理のため、コールバックを使用して処理の完了を知らせる必要があります。...


Intl.DateTimeFormatを使って日付をyyyy-mm-dd形式でフォーマットする方法

Dateオブジェクトには、日付を文字列に変換するtoString()メソッドがあります。このメソッドの引数に書式文字列を指定することで、希望する形式で日付を取得することができます。toString()メソッドで使用できる書式文字列は以下の通りです。...


Angular 2 Karma テストで "component-name' is not a known element" エラーが発生する原因と解決方法

原因と解決方法コンポーネント名が正しく記述されていないテストコード内でコンポーネント名を正しく記述しているか確認してください。スペルミスや大文字・小文字の誤りがないか注意が必要です。例:上記の例では、MyComponent コンポーネント名が正しく記述されています。...


SQL SQL SQL SQL Amazon で見る



CSSのwhite-spaceとoverflow-wrapプロパティでテキストを折り返す

そこで、この問題を解決するために、CSSの以下の2つのプロパティを使用できます。white-space: このプロパティは、テキスト内の空白文字の扱い方を指定します。overflow-wrap: このプロパティは、長い単語やテキストが要素の幅を超えた場合の折り返し方法を指定します。


JSON.stringify()を使いこなす:詳細ガイド

JSON. stringify()は、JSONオブジェクトを文字列に変換する関数です。オプションでスペースやタブを指定することで、整形された文字列を出力できます。上記のコードは、JSONオブジェクトを2スペースのインデントで整形して出力します。


エンジニア必見!HTML改行問題を解決する3つの方法とサンプルコード

方法 1: <pre> タグを使用する最も簡単な方法は、<pre> タグを使用することです。<pre> タグは、ブラウザにテキストを事前フォーマットされたものとして表示するように指示します。これにより、スペースと改行が保持されます。<br> タグを使用して、改行を挿入することもできます。ただし、これはスペースを保持しません。