javascript jsonファイルを指定して読み込む

javascript jsonファイルを指定して読み込む

javascriptで、jsonファイルを指定して読み込むサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.81

jsonファイルを指定して読み込む

jsonファイルを指定して読み込むには、以下のように「module」として「js」を読み込み、その中で処理を、実行します。

<script type="module" src="test.js"></script>

実際に、以下の「test.json」というファイルを読み込んでみます。

{
    "person": {
      "name": "mebee",
      "age": 20,
      "address": ["tokyo", "japan"]      
    }
}  

「test.js」を作成して「module」として読み込みます。

<script type="module" src="test.js"></script>

「test.js」で、jsonファイルを「import」します。

import test from './test.json' assert {type: 'json'};

console.log(test.person);

console.log(test.person.name);
console.log(test.person.address);

実行結果を見ると「json」ファイルが読み込みされていることが確認できます。

※fireforx102やsafari15.5ではエラーとなり、使用できません。

<firefox 102>
Uncaught SyntaxError: import assertions are not currently supported

<safari 15.5>
SyntaxError: Unexpected identifier 'assert'. Expected a ';' following a targeted import declaration.

サンプルコード

以下は、
「取得」ボタンをクリックした際に、指定したjsonファイルを読み込んで表示するだけのサンプルコードとなります。

※cssには「material bootstrap」を使用して、アロー関数で関数は定義してます。

読み込むjsonファイル「test.json」は、以下で、

{ "a" : 100, "b" : 200, "c" : 300 }

使用するjsファイル「test.js」は、以下となります。

import test from './test.json' assert {type: 'json'};

const hoge = () => {

    let text = [];

    for (let item in test) {
        text.push('<li class="list-group-item">' + item + '</li>');
    };

    //innerHTMLを使用して表示    
    txt.innerHTML = text.join('');

}

// クリックイベントを登録
document.getElementsByClassName("btn")[0].onclick = () => { hoge() };

表示用のhtmlファイルは、以下の内容となります。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-50 mx-auto" style="margin-top:200px">

    <h2><span class="badge bg-primary">表示</span></h2>
    <ul id="txt" class="list-group"></ul>

    <button type="button" onclick="hoge()" class="btn btn-info">
      取得
    </button>

  </div>

  <script type="module" src="test.js"></script>

</body>

</html>

実行結果を確認すると、jsonファイルを読み込んで表示されていることが確認できます。