1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

response.json()とは? - 中学生でもわかる解説

Posted at

response.json()って何?

response.json()は、サーバーから受け取ったデータを、JavaScriptで使える形に変換する魔法の言葉です。

簡単に言うと

サーバーから届いたデータは「文字列」の状態です。
それを「JavaScriptのオブジェクト」に変換するのがresponse.json()です。

// サーバーから届くデータ(文字列)
'{"name": "太郎", "age": 15}'

// ↓ response.json() で変換

// JavaScriptで使えるオブジェクト
{ name: "太郎", age: 15 }

なぜ必要なの?

問題:そのままでは使えない

const response = await fetch('https://api.example.com/user/1');

// このresponseには文字列でデータが入っている
console.log(response); // Response オブジェクト(中身が見えない)

// ❌ これはできない
console.log(response.name); // undefined

解決:json()で変換する

const response = await fetch('https://api.example.com/user/1');

// json()で変換!
const data = await response.json();

// ✅ これでアクセスできる
console.log(data.name); // "太郎"
console.log(data.age);  // 15

基本的な使い方

ステップ1:データを取得

const response = await fetch('https://api.example.com/products/1');

この時点では、まだデータは使えない状態です。

ステップ2:json()で変換

const product = await response.json();

これでJavaScriptのオブジェクトになります。

ステップ3:データを使う

console.log(product.name);  // "スマートフォン"
console.log(product.price); // 50000

完全な例

async function getProduct() {
  // 1. データを取得
  const response = await fetch('https://api.shop.com/products/123');
  
  // 2. json()で変換
  const product = await response.json();
  
  // 3. データを使う
  console.log('商品名:', product.name);
  console.log('価格:', product.price);
  console.log('在庫:', product.stock);
}

getProduct();

なぜawaitが必要?

response.json()時間がかかる処理なので、awaitで待つ必要があります。

❌ awaitを忘れると

const response = await fetch('https://api.example.com/user');
const data = response.json(); // awaitがない!

console.log(data); // Promise {<pending>} ← 変な値
console.log(data.name); // エラー!

✅ awaitをつけると

const response = await fetch('https://api.example.com/user');
const data = await response.json(); // awaitをつける

console.log(data); // { name: "太郎", age: 15 } ← 正しい値
console.log(data.name); // "太郎"

JSONって何?

JSON(ジェイソン)= JavaScript Object Notation

データをやり取りするための「書き方のルール」です。

JSONの見た目

{
  "name": "太郎",
  "age": 15,
  "hobbies": ["読書", "ゲーム"],
  "address": {
    "city": "東京",
    "country": "日本"
  }
}

特徴:

  • キーは必ず""(ダブルクォート)で囲む
  • 文字列も""で囲む
  • JavaScriptのオブジェクトに似ている

response.json()の役割

サーバー → JSON文字列 → response.json() → JavaScriptオブジェクト

実際の使用例

例1:ユーザー情報の取得

async function showUserProfile() {
  try {
    const response = await fetch('https://api.example.com/users/123');
    const user = await response.json();
    
    console.log('ユーザー名:', user.name);
    console.log('メール:', user.email);
    console.log('登録日:', user.createdAt);
    
  } catch (error) {
    console.log('エラーが発生しました');
  }
}

showUserProfile();

サーバーから返ってくるJSON:

{
  "id": 123,
  "name": "山田太郎",
  "email": "taro@example.com",
  "createdAt": "2024-01-15"
}

例2:商品リストの取得

async function showProducts() {
  const response = await fetch('https://api.shop.com/products');
  const products = await response.json();
  
  // 配列の場合
  products.forEach(product => {
    console.log('商品:', product.name);
    console.log('価格:', product.price + '');
    console.log('---');
  });
}

showProducts();

サーバーから返ってくるJSON:

[
  {
    "id": 1,
    "name": "スマートフォン",
    "price": 50000
  },
  {
    "id": 2,
    "name": "ノートPC",
    "price": 100000
  }
]

例3:Next.jsでの使用

// app/products/[id]/page.jsx
export default async function ProductPage({ params }) {
  // 1. fetch でデータ取得
  const response = await fetch(
    `https://api.shop.com/products/${params.id}`
  );
  
  // 2. json() で変換
  const product = await response.json();
  
  // 3. データを表示
  return (
    <div>
      <h1>{product.name}</h1>
      <p>価格: {product.price}</p>
      <p>説明: {product.description}</p>
      <img src={product.image} alt={product.name} />
    </div>
  );
}

エラー処理

基本的なエラー処理

async function getUser() {
  try {
    const response = await fetch('https://api.example.com/users/1');
    
    // レスポンスが正常かチェック
    if (!response.ok) {
      throw new Error('データ取得に失敗しました');
    }
    
    const user = await response.json();
    console.log(user);
    
  } catch (error) {
    console.log('エラー:', error.message);
  }
}

response.okとは?

response.ok = サーバーからの応答が成功(ステータスコード200-299)かどうか

const response = await fetch('https://api.example.com/user/999');

console.log(response.status); // 404
console.log(response.ok);     // false

if (response.ok) {
  const data = await response.json();
  console.log(data);
} else {
  console.log('データが見つかりません');
}

詳細なエラー処理

async function getProduct(id) {
  try {
    const response = await fetch(`https://api.shop.com/products/${id}`);
    
    // ステータスコードで分岐
    if (response.status === 404) {
      console.log('商品が見つかりません');
      return null;
    }
    
    if (response.status === 500) {
      console.log('サーバーエラーが発生しました');
      return null;
    }
    
    if (!response.ok) {
      console.log('不明なエラーが発生しました');
      return null;
    }
    
    // 正常な場合のみjson()を実行
    const product = await response.json();
    return product;
    
  } catch (error) {
    console.log('通信エラー:', error.message);
    return null;
  }
}

JSONが壊れている場合

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    
    // json()自体がエラーになることもある
    const data = await response.json();
    console.log(data);
    
  } catch (error) {
    // JSONのパースに失敗した場合もここに来る
    console.log('データの解析に失敗しました');
  }
}

response.json()以外のメソッド

text() - 文字列として取得

const response = await fetch('https://example.com/data.txt');
const text = await response.text();

console.log(text); // "こんにちは、世界!"

使い所:

  • HTMLファイルを取得
  • プレーンテキストを取得

blob() - 画像やファイル

const response = await fetch('https://example.com/image.jpg');
const blob = await response.blob();

// 画像として表示
const url = URL.createObjectURL(blob);
document.querySelector('img').src = url;

使い所:

  • 画像のダウンロード
  • ファイルのダウンロード

arrayBuffer() - バイナリデータ

const response = await fetch('https://example.com/file.pdf');
const buffer = await response.arrayBuffer();

console.log(buffer); // ArrayBuffer

使い所:

  • PDFファイル
  • 音声・動画ファイル

使い分けのまとめ

// JSON(オブジェクト・配列)を受け取る
const data = await response.json();

// テキストを受け取る
const text = await response.text();

// 画像・ファイルを受け取る
const blob = await response.blob();

// バイナリデータを受け取る
const buffer = await response.arrayBuffer();

よくあるパターン

パターン1:複数のデータを取得

async function getAllData() {
  try {
    // 3つのAPIを同時に呼び出す
    const [userRes, postsRes, commentsRes] = await Promise.all([
      fetch('https://api.example.com/user/1'),
      fetch('https://api.example.com/posts'),
      fetch('https://api.example.com/comments')
    ]);
    
    // 全てjson()で変換
    const user = await userRes.json();
    const posts = await postsRes.json();
    const comments = await commentsRes.json();
    
    console.log('ユーザー:', user);
    console.log('投稿数:', posts.length);
    console.log('コメント数:', comments.length);
    
  } catch (error) {
    console.log('エラー:', error.message);
  }
}

パターン2:ページネーション

async function getPosts(page = 1) {
  const response = await fetch(
    `https://api.blog.com/posts?page=${page}&limit=10`
  );
  const data = await response.json();
  
  return {
    posts: data.posts,      // 投稿の配列
    totalPages: data.total, // 全ページ数
    currentPage: page       // 現在のページ
  };
}

// 使用例
const result = await getPosts(1);
console.log('投稿一覧:', result.posts);
console.log('全ページ数:', result.totalPages);

パターン3:検索機能

async function searchProducts(keyword) {
  try {
    const response = await fetch(
      `https://api.shop.com/search?q=${encodeURIComponent(keyword)}`
    );
    
    if (!response.ok) {
      throw new Error('検索に失敗しました');
    }
    
    const results = await response.json();
    
    if (results.length === 0) {
      console.log('検索結果が見つかりませんでした');
      return [];
    }
    
    console.log(`${results.length}件見つかりました`);
    return results;
    
  } catch (error) {
    console.log('エラー:', error.message);
    return [];
  }
}

// 使用例
const products = await searchProducts('スマートフォン');
products.forEach(product => {
  console.log(product.name, product.price);
});

パターン4:データの投稿(POST)

async function createPost(title, content) {
  try {
    const response = await fetch('https://api.blog.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: title,
        content: content
      })
    });
    
    if (!response.ok) {
      throw new Error('投稿に失敗しました');
    }
    
    // サーバーからの返事もjson()で受け取る
    const result = await response.json();
    
    console.log('投稿成功!');
    console.log('投稿ID:', result.id);
    return result;
    
  } catch (error) {
    console.log('エラー:', error.message);
    return null;
  }
}

// 使用例
await createPost('新しい記事', 'これは記事の内容です');

Next.jsでの実践例

例1:商品詳細ページ

// app/products/[id]/page.jsx
export default async function ProductPage({ params }) {
  try {
    const response = await fetch(
      `https://api.shop.com/products/${params.id}`,
      {
        next: { revalidate: 60 } // 60秒キャッシュ
      }
    );
    
    if (!response.ok) {
      return (
        <div>
          <h1>商品が見つかりません</h1>
          <p>この商品は存在しないか削除されました</p>
        </div>
      );
    }
    
    const product = await response.json();
    
    return (
      <div>
        <h1>{product.name}</h1>
        <img src={product.image} alt={product.name} />
        <p className="price">{product.price.toLocaleString()}</p>
        <p>{product.description}</p>
        <button>カートに追加</button>
      </div>
    );
    
  } catch (error) {
    return (
      <div>
        <h1>エラーが発生しました</h1>
        <p>時間をおいて再度お試しください</p>
      </div>
    );
  }
}

例2:ブログ記事一覧

// app/blog/page.jsx
export default async function BlogPage() {
  const response = await fetch('https://api.blog.com/posts', {
    cache: 'no-store' // キャッシュしない(常に最新)
  });
  
  const posts = await response.json();
  
  return (
    <div>
      <h1>ブログ記事一覧</h1>
      <div className="posts">
        {posts.map(post => (
          <article key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.excerpt}</p>
            <a href={`/blog/${post.slug}`}>続きを読む </a>
          </article>
        ))}
      </div>
    </div>
  );
}

例3:ユーザーダッシュボード

// app/dashboard/page.jsx
export default async function DashboardPage() {
  try {
    // 複数のAPIを同時に呼び出す
    const [userRes, statsRes, notificationsRes] = await Promise.all([
      fetch('https://api.example.com/user/me'),
      fetch('https://api.example.com/stats'),
      fetch('https://api.example.com/notifications')
    ]);
    
    // 全てチェック
    if (!userRes.ok || !statsRes.ok || !notificationsRes.ok) {
      throw new Error('データの取得に失敗しました');
    }
    
    // 全てjson()で変換
    const user = await userRes.json();
    const stats = await statsRes.json();
    const notifications = await notificationsRes.json();
    
    return (
      <div>
        <h1>ようこそ{user.name}さん</h1>
        
        <section>
          <h2>統計情報</h2>
          <p>投稿数: {stats.posts}</p>
          <p>フォロワー: {stats.followers}</p>
          <p>いいね: {stats.likes}</p>
        </section>
        
        <section>
          <h2>お知らせ ({notifications.length})</h2>
          {notifications.map(notif => (
            <div key={notif.id}>
              <p>{notif.message}</p>
              <small>{notif.createdAt}</small>
            </div>
          ))}
        </section>
      </div>
    );
    
  } catch (error) {
    return (
      <div>
        <h1>データの読み込みに失敗しました</h1>
        <p>ページを再読み込みしてください</p>
      </div>
    );
  }
}

よくある質問

Q1: json()は必ず必要?

A: JSONデータを受け取る時は必要です。

// JSONを受け取る → json()が必要
const response = await fetch('https://api.example.com/data');
const data = await response.json(); // 必要!

// テキストを受け取る → text()を使う
const response = await fetch('https://example.com/data.txt');
const text = await response.text();

// 画像を受け取る → blob()を使う
const response = await fetch('https://example.com/image.jpg');
const blob = await response.blob();

Q2: json()を2回呼べる?

A: いいえ、1回だけです。

const response = await fetch('https://api.example.com/data');

const data1 = await response.json(); // OK
const data2 = await response.json(); // エラー!もう読み取れない

対策:変数に保存して使い回す

const response = await fetch('https://api.example.com/data');
const data = await response.json();

// dataを何度でも使える
console.log(data.name);
console.log(data.age);

Q3: json()が遅い時は?

A: サーバーからのレスポンスが大きいか、通信が遅い可能性があります。

async function getData() {
  console.log('データ取得開始...');
  
  const response = await fetch('https://api.example.com/large-data');
  
  console.log('データ受信完了、解析中...');
  
  const data = await response.json(); // ここで時間がかかる
  
  console.log('解析完了!');
  return data;
}

対策:

  • サーバー側でデータを圧縮する
  • 必要なデータだけを取得する
  • ページネーションを使う

Q4: JSONじゃないデータにjson()を使うとどうなる?

A: エラーになります。

// HTMLを取得
const response = await fetch('https://example.com/page.html');

try {
  const data = await response.json(); // エラー!
} catch (error) {
  console.log('JSONではありません');
}

// 正しくはtext()を使う
const html = await response.text();

よくある間違い

間違い1: awaitを忘れる

// ❌ これは間違い
const response = await fetch('https://api.example.com/data');
const data = response.json(); // awaitがない!

console.log(data); // Promise {<pending>}
console.log(data.name); // エラー!

// ✅ これが正しい
const response = await fetch('https://api.example.com/data');
const data = await response.json(); // awaitをつける

console.log(data); // { name: "太郎", ... }
console.log(data.name); // "太郎"

間違い2: エラーチェックを忘れる

// ❌ 危険(エラーの時に止まる)
const response = await fetch('https://api.example.com/data');
const data = await response.json();

// ✅ 安全(エラーに対応)
const response = await fetch('https://api.example.com/data');

if (!response.ok) {
  console.log('エラーが発生しました');
  return;
}

const data = await response.json();

間違い3: 間違ったメソッドを使う

// ❌ テキストデータにjson()を使う
const response = await fetch('https://example.com/data.txt');
const data = await response.json(); // エラー!

// ✅ text()を使う
const response = await fetch('https://example.com/data.txt');
const text = await response.text();

まとめ

response.json()の本質

サーバーから受け取ったJSONデータを、JavaScriptで使えるオブジェクトに変換する

基本の流れ

// 1. データを取得
const response = await fetch('URL');

// 2. エラーチェック
if (!response.ok) {
  console.log('エラー');
  return;
}

// 3. json()で変換
const data = await response.json();

// 4. データを使う
console.log(data.name);

覚えておくこと

  1. json()には必ずawaitをつける

    • 時間がかかる処理だから
  2. response.okでエラーチェック

    • 失敗した時の対策を忘れずに
  3. json()は1回だけ

    • 変数に保存して使い回す
  4. データ形式に合わせてメソッドを選ぶ

    • JSON → json()
    • テキスト → text()
    • 画像 → blob()

最も大事なこと:
response.json()は「文字列→オブジェクト」への変換器。これがないと、サーバーから受け取ったデータは使えない!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?