JSON - Javascript

JSON ファイルを扱う

JSON の記述をする際に次の3つの注意点があります。

  • キーをダブルクォーテーションで囲む
  • シングルクォーテーションは使えない
  • 配列の最後の要素の後ろに ,(カンマ)を入れてはいけない
let json = '{ "name" : "Taro", "age" : 20 }';
console.log(typeof(json)); // string

let encode_data = JSON.parse(json);
console.log(typeof(encode_data)); // object

let decode_data = JSON.stringify(json);
console.log(typeof(decode_data)) // string

JSON の値を取得

let json = '[{ "name" : "Taro", "age" : 20 }, { "name" : "Jiro", "age" : 25}]';
let encode_data = JSON.parse(json);

console.log(json[0]["name"]); // undefined
console.log(encode_data[0]["name"]); // Taro

encode_data.forEach(function(data){
    console.log(data["name"]);
});

// 結果
Taro
Jiro

ローカルの JSON ファイルを読み込む

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <title>sample</title>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <form>
    <input id="myfile" type="file" />
  </form>
</body>
</html>

script.js

window.onload = function(){
  var target = document.getElementById('myfile')

  target.addEventListener( 'change', function(e) {

    const reader = new FileReader();

    const file = e.target.files[0];

    reader.readAsText( file );
    
    reader.addEventListener('load', function(){
      let encode_data = JSON.parse(reader.result)
      encode_data.forEach(function(data){
        console.log(data["os"]);
      })
    })
  })
}