
JavaScriptのイベント処理:クリック、フォーム入力からバブリング・デリゲーションまで
はじめに JavaScriptのイベント処理は、インタラクティブなウェブアプリケーション開発の核心です。ユーザーのクリック、フォーム入力、キーボード操作など、あ […]
JSON(JavaScript Object Notation)は、軽量なデータ交換フォーマットです。JavaScriptのオブジェクト表記法に基づいていますが、独立したデータ形式として多くのプログラミング言語でサポートされています。
" "
で囲む "Hello, World!"
42
3.14159
true
false
null
[]
で囲む [1, 2, 3, "four", true]
{}
で囲み、"key": value
のペアで構成 {
"name": "山田太郎",
"age": 30,
"isStudent": false
}
const jsonString = '{"name":"山田太郎","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "山田太郎"
const user = {
name: "山田太郎",
age: 30,
hobbies: ["読書", "プログラミング"]
};
const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"山田太郎","age":30,"hobbies":["読書","プログラミング"]}'
// 特定のプロパティのみ含める
const json = JSON.stringify(user, ["name", "age"]);
console.log(json); // '{"name":"山田太郎","age":30}'
// 関数で変換を制御
const json = JSON.stringify(user, (key, value) => {
if (key === "age") return undefined; // ageプロパティを除外
return value;
});
// 整形出力(人間が読みやすい形式)
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
/*
{
"name": "山田太郎",
"age": 30,
"hobbies": [
"読書",
"プログラミング"
]
}
*/
const person = {
name: "山田太郎",
age: 30,
toJSON() {
return {
fullName: this.name,
years: this.age
};
}
};
console.log(JSON.stringify(person));
// '{"fullName":"山田太郎","years":30}'
// APIからデータ取得
fetch('https://api.example.com/users')
.then(response => response.json()) // JSONをパース
.then(data => console.log(data))
.catch(error => console.error(error));
// データ送信
const newUser = { name: "花子", age: 25 };
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
});
// 保存
const settings = { theme: "dark", fontSize: 14 };
localStorage.setItem('userSettings', JSON.stringify(settings));
// 読み取り
const savedSettings = JSON.parse(localStorage.getItem('userSettings'));
console.log(savedSettings.theme); // "dark"
// config.json
{
"apiUrl": "https://api.example.com",
"maxRetries": 3,
"timeout": 5000
}
// JavaScriptで読み込み
fetch('config.json')
.then(response => response.json())
.then(config => {
console.log(`API URL: ${config.apiUrl}`);
});
JSONデータの構造を定義・検証する仕様です。
// person.schema.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number", "minimum": 0 }
},
"required": ["name"]
}
eval()
を使用しない // 危険な例
const obj = eval('(' + jsonString + ')');
// 安全な例
const obj = JSON.parse(jsonString);
stream-json
というライブラリを使った安全なJSONストリーミング解析例
const fs = require('fs');
const { parser } = require('stream-json');
const { streamArray } = require('stream-json/streamers/StreamArray');
const jsonStream = fs.createReadStream('huge.json')
.pipe(parser())
.pipe(streamArray());
jsonStream.on('data', ({ key, value }) => {
// 要素ごとに安全に処理できる
console.log(`Key: ${key}, Value:`, value);
});
jsonStream.on('end', () => {
console.log('JSON parsing complete.');
});
JSON.stringify()
でエラーが発生オブジェクト内で自分自身を参照している(または互いに参照し合っている)と、JSON.stringify()
はエラーになります。
const obj = { a: 1 };
obj.self = obj;
JSON.stringify(obj); // TypeError
const book = {
title: "JavaScript入門",
price: 2500,
inStock: true
};
author
プロパティにアクセスしなさい。 {
"title": "JSONガイド",
"author": "山田太郎",
"published": false
}
{
name: "エラー例",
"values": [1, 2, 3],
"active": true,
}
password
プロパティが含まれないようにしなさい。 const user = {
username: "js_user",
password: "secret123",
email: "user@example.com"
};
age
が30以上の人のname
だけを含む配列を作成しなさい。 [
{ "name": "太郎", "age": 25 },
{ "name": "花子", "age": 30 },
{ "name": "次郎", "age": 35 }
]
street
の値を取得しなさい。 {
"user": {
"name": "山田太郎",
"address": {
"city": "東京",
"street": "渋谷区1-2-3"
}
}
}
const obj1 = { "a": 1, "b": 2 };
const obj2 = { "b": 3, "c": 4 };
{"name":"整形例","values":[1,2,3],"active":true}
const obj = { date: new Date() };
console.log(JSON.stringify(obj));
"[Circular]"
という文字列に変換)。const obj = { a: 1 };
obj.self = obj;
const jsonString = JSON.stringify(book);
// '{"title":"JavaScript入門","price":2500,"inStock":true}'
const jsonObj = JSON.parse('{"title":"JSONガイド","author":"山田太郎","published":false}');
console.log(jsonObj.author); // "山田太郎"
name
がダブルクォートで囲まれていない {
"name": "エラー例", // nameもダブルクウォートで囲む
"values": [1, 2, 3],
"active": true // 最後のプロパティはカンマなし
}
const json = JSON.stringify(user, (key, val) =>
key === "password" ? undefined : val
);
const people = JSON.parse('[{"name":"太郎","age":25},{"name":"花子","age":30},{"name":"次郎","age":35}]');
const names = people.filter(p => p.age >= 30).map(p => p.name);
const data = JSON.parse('{"user":{"name":"山田太郎","address":{"city":"東京","street":"渋谷区1-2-3"}}}');
const street = data.user.address.street;
const merged = JSON.stringify({ ...obj1, ...obj2 });
// '{"a":1,"b":3,"c":4}'
const jsonObj = JSON.parse('{"name":"整形例","values":[1,2,3],"active":true}');
console.log(JSON.stringify(jsonObj, null, 2));
{“date”:”2023-05-01T00:00:00.000Z”}
const obj = { date: new Date() };
console.log(JSON.stringify(obj)); // {"date":"2023-10-01T00:00:00.000Z"}
// DateオブジェクトはJSON.stringify()で文字列に変換される
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
});
}
const fs = require('fs');
const { parse } = require('JSONStream');
const stream = fs.createReadStream('large.json') .pipe(parse('*'));
stream.on('data', data => { // データを逐次処理 console.log(data); });
json {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 1
},
"name": {
"type": "string"
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
"maxItems": 5
}
},
"required": ["id", "name"]
}