ブラウザ環境でJSONファイルを読み込む - TypeScriptとfetch API
TypeScriptでJSONファイルを読み込む
importキーワードを使用する
これは最もシンプルで一般的な方法です。JSONファイルがプロジェクトと同じディレクトリにある場合、以下のコードのようにimport
キーワードを使って読み込むことができます。
import jsonData from './data.json';
// jsonDataはJSONファイルの内容を表すオブジェクトになります
console.log(jsonData.name); // 例: "John Doe"
JSONファイルが別のディレクトリにある場合は、相対パスまたは絶対パスを使って指定する必要があります。
import jsonData from '../data/user.json';
// ...
require関数を使用する
Node.js環境で開発している場合は、require
関数を使ってJSONファイルを読み込むことができます。
const jsonData = require('./data.json');
// ...
require
関数は非同期処理なので、読み込み完了後に処理を行う場合はコールバック関数を使用する必要があります。
const jsonData = require('./data.json', (err, data) => {
if (err) {
throw err;
}
// jsonDataはJSONファイルの内容を表すオブジェクトになります
console.log(jsonData.name); // 例: "John Doe"
});
fetch APIを使用する
const url = './data.json';
fetch(url)
.then(response => response.json())
.then(jsonData => {
// jsonDataはJSONファイルの内容を表すオブジェクトになります
console.log(jsonData.name); // 例: "John Doe"
})
.catch(err => {
throw err;
});
型定義
JSONファイルの内容を型付きで読み込む場合は、interface
やtype
を使って型定義ファイルを作成する必要があります。
例えば、以下のJSONファイルを読み込む場合
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main Street",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
以下の型定義ファイルを作成することができます。
interface User {
name: string;
age: number;
address: Address;
}
interface Address {
street: string;
city: string;
state: string;
zip: string;
}
型定義ファイルを作成したら、import
キーワードを使って読み込み、型を指定することができます。
import { User } from './data.json';
const user: User = jsonData;
// userはUser型のオブジェクトになります
console.log(user.name); // 例: "John Doe"
console.log(user.address.city); // 例: "New York"
TypeScriptでJSONファイルを読み込む方法はいくつかあります。どの方法を使うかは、開発環境や目的に合わせて選択してください。
importキーワードを使用する
// data.jsonの内容
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main Street",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
// index.ts
import { User } from './data.json';
const user: User = jsonData;
console.log(user.name); // 例: "John Doe"
console.log(user.address.city); // 例: "New York"
require関数を使用する
// data.jsonの内容
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main Street",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
// index.ts
const jsonData = require('./data.json');
console.log(jsonData.name); // 例: "John Doe"
console.log(jsonData.address.city); // 例: "New York"
fetch APIを使用する
// data.jsonの内容
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main Street",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
// index.ts
const url = './data.json';
fetch(url)
.then(response => response.json())
.then(jsonData => {
console.log(jsonData.name); // 例: "John Doe"
console.log(jsonData.address.city); // 例: "New York"
})
.catch(err => {
throw err;
});
実行方法
tsc index.ts
node index.js
JSON.parse
関数は、JSON文字列をJavaScriptオブジェクトに変換するために使用できます。
const jsonData = JSON.parse('{"name": "John Doe", "age": 30}');
console.log(jsonData.name); // 例: "John Doe"
console.log(jsonData.age); // 例: 30
ただし、この方法では型安全性がないため、JSONファイルの内容が正しくない場合、エラーが発生する可能性があります。
TypeScriptのJSON型を使用する
TypeScript 2.9以降では、JSON
型を使用してJSONファイルを型付きで読み込むことができます。
const jsonData: JSON = require('./data.json');
console.log(jsonData.name); // 例: "John Doe"
console.log(jsonData.address.city); // 例: "New York"
ただし、この方法では、JSONファイルの内容の型を個別に指定することができないため、型安全性は完全ではありません。
ライブラリを使用する
jsonfile
やfs-extra
などのライブラリを使用することで、より簡単にJSONファイルを読み込むことができます。
import * as jsonfile from 'jsonfile';
jsonfile.readFile('./data.json', (err, jsonData) => {
if (err) {
throw err;
}
console.log(jsonData.name); // 例: "John Doe"
console.log(jsonData.address.city); // 例: "New York"
});
これらのライブラリは、型安全性やエラー処理などの機能を提供しているため、より安全で効率的にJSONファイルを読み込むことができます。
json typescript