0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSONとは何かについて改めて整理してみた

Posted at

JSONとは何かについて改めて整理してみた

JSON(JavaScript Object Notation)は、データをシンプルなテキスト形式で表現する軽量のデータ交換フォーマットである。人間にとって読み書きが容易であり、機械にとっても解析や生成が簡単なため、さまざまなシステム間のデータ通信に適している。

JSONの基本的な構造は2つある。

  1. 名前/値のペアの集まり(オブジェクト)
  2. 値の順序付きリスト(配列)

これらの構造により、JSONはWeb APIのレスポンスや設定ファイルとして広く活用されている。

参考:MDN JSONの基本

JSONはどんなときに使うのか?

1. アプリやWebのデータ通信

iOSアプリやWebアプリでは、サーバーと情報をやり取りする際にJSONをよく使う。例えば、天気アプリがサーバーから最新の天気情報を取得する場合、サーバーは以下のようなJSONデータを送信する。

{
  "location": "Tokyo",
  "temperature": 18,
  "weather": "cloudy"
}

このデータを基に、アプリは「東京の気温は18度、天気はくもり」と表示する。

2. 設定情報の保存

JSONは設定ファイルとしても利用される。例えば、アプリのユーザー設定をJSON形式で保存すれば、次回起動時に同じ設定を適用できる。

{
  "username": "taro123",
  "theme": "dark",
  "notifications": true
}

このデータを保存しておけば、アプリ再起動時に「ユーザー名:taro123」「ダークモード」「通知オン」の設定を復元可能。


SwiftでのJSONの使用方法

1. JSONのデコード(解析)

JSONDecoderを使えば、JSONデータをSwiftのデータ型に変換できる。

import Foundation

struct Weather: Codable {
    let location: String
    let temperature: Int
    let weather: String
}

let url = URL(string: "https://example.com/weather.json")!

URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    
    do {
        let weather = try JSONDecoder().decode(Weather.self, from: data)
        print("場所: \(weather.location), 気温: \(weather.temperature)℃, 天気: \(weather.weather)")
    } catch {
        print("JSONの解析に失敗しました: \(error)")
    }
}.resume()

2. JSONのエンコード(生成)

SwiftのデータをJSON形式に変換するには、JSONEncoderを使用する。

import Foundation

struct UserProfile: Codable {
    let username: String
    let age: Int
}

let user = UserProfile(username: "taro123", age: 20)

do {
    let jsonData = try JSONEncoder().encode(user)
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString) // {"username":"taro123","age":20}
    }
} catch {
    print("JSONの変換に失敗しました: \(error)")
}

まとめ

  • JSONはデータ交換や設定ファイルで広く使われるフォーマット
  • Swiftでは**Codable**を使うとJSONのエンコード・デコードが簡単
  • 他のデータフォーマットと比較して、用途に応じた選択が重要

さらに詳しく学ぶなら、以下の公式ドキュメントを参照。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?