Skip to main content

JSONとPHP

JSONのファイル形式について

JSON is a way to store and organize data inside a text file. It is frequently used in web applications to send data between the client and the server.JSONとは、テキストファイルの中にデータを保存し、整理するための方法である。ウェブアプリケーションでよく使われていて、クライアントとサーバーの間でデータをやりとりするときによく使われる。

JSON files store a combination of dictionaries (associative arrays) and indexed arrays. Please note that in JSON, dictionaries are called "objects"JSONファイルの中では、辞書(連想配列)と添字付き配列を組み合わせてデータを保存する。JSONでは辞書のことを「オブジェクト」と呼ぶので、注意してほしい。

Objectsオブジェクト(Object)

Objectsオブジェクトとは、キーと値のペアをコンマで区切って集めたもので、下のように中かっこ({ are a collection of pairs of keys and values, separated by commas, stored between curly braces like so})の中に書く。

{
    "key 1" : "value 1",
    "key 2" : "value 2",
    ...
    "key n" : "value n"
}

where "key" is always a string (defined between quotation marks) and value can be one of the following types:ここで「キー」は必ず文字列(引用符で囲んで書く)であり、「値」は次のいずれかの種類になる。

String (between quotation marks)文字列(引用符で囲む)

"player_name" : "ウルトラマン"
Integer numbers整数
 "XP" : 12345
Floating point numbers浮動小数点数(小数)
"distance" : 31.145
Boolean (真偽値(true / false)false)
"success" : true
Other object or arrayほかのオブジェクトや配列
"item_data" : 
  { 
    "name:" : "魔法のマント",
    "cost"  : 300
  }

Arrays配列(Array)

Arrays配列とは、順番に並んだ値の集まりで、ふつうは同じ種類の値が入る。配列は角かっこ([ are sequential values, usually of the same type. Arrays are defined by square brackets:])を使って定義する。

[
  "Apple", 
  "Banana", 
  "Grape"
]

JSON does allow mixed types within the same array. While strange, this is also possible:JSONでは、同じ配列の中に違う種類の値を混ぜることもできる。少し変に見えるかもしれないが、これも可能である。

[
  "Apple", 
  25, 
  false
]

Example

A JSON file must always start with an curly brace (as an object), or with a square bracket (as an array). In our practice, we'll prefer starting as an object, since it is easier to understand.JSONファイルは必ず、中かっこ(オブジェクトとして)か、角かっこ(配列として)のどちらかから始まる。この授業では、わかりやすいのでオブジェクトから始める形を使っていく。

Let's imagine A JSON that handles data about a save game. We want to store the date, the XP, HP, and list of stages cleared. It would look something like this:セーブデータを扱うJSONを考えてみよう。日付、XP、HP、そしてクリアしたステージのリストを保存したいとする。すると、下のようになる。

{
	"save_date" : "2026-07-14",
	"save_time" : "11:45",
	"XP" : 54796
	"HP" : 97.15
	"stage_cleared" : [true, true, false, false, true, false]
}

JSONとPHPのデータ変換

Since JSON is used a lot in web contexts, PHP provides two functions to convert a PHP associative array into JSON text and vice-versa.JSONはウェブの場面でよく使われるため、PHPには次の2つの関数が用意されている。ひとつはPHPの連想配列をJSONのテキストに変換する関数、もうひとつはその逆の変換をする関数である。

From PHP associative array to JSON text:PHPの連想配列からJSONテキストへ
$json = json_encode($dictionary);
From JSON text to PHP associative arrayJSONテキストからPHPの連想配列へ
$dictionary = json_decode($json, true);

練習

Let's take what we saw and run a little exercise.ここまで見てきたことを使って、簡単な練習をしてみよう。

  • Download this JSON fileこのJSONファイル and place it in your local XAMPP webserver (をダウンロードし、自分のパソコンのXAMPPウェブサーバー(C:\xampp\htdocs).htdocs)の中に置いてください。
  • LoadPHPの命令 thefile_get_contents JSON file using the PHP instruction file_get_contents (textbook page 80)を使って、このJSONファイルを読み込んでください(教科書80ページ)。
  • Changesave_date the save_datesave_time and save_time to current time and date (textbook page 40)を、今の日付と時刻に変更してください(教科書40ページ)。
  • Mark the third stage (index 2), as cleared (set to true)3つ目のステージ(インデックス2)をクリア済みにしてください(trueにする)。
  • Convert back to JSON text もう一度JSONのテキストに変換してください。
  • Display the JSON text so the browser can display itブラウザに表示されるように、そのJSONテキストを出力してください。
test_json.php
<?php	
	// JSONを読み込む(テキスト)
	$json = file_get_contents("save_slot.json");

	// PHPの連想配列へ変換
	$data = json_decode($json, true);
	
	// 現在の日時にする
	$data["save_date"] = date("Y-m-d");
	$data["save_time"] = date("H:i:s");
	
	// 3つ目のステージをクリアにする
	$data["stage_cleared"][2] = true;
	
	// またJSONへ
	$json = json_encode($data);
	
	// 表示(返す)
	print($json);
?>

 

Explicitly returning JSONJSONだと明示して返す

By default, Apache (the webserver) assumes that the result is an HTML file, so it tells the browser to expect an HTML file. It does so, by defining a "header", in which the type of the data is defined. These are known as MIME types and you can find a list here初期設定では、Apache(ウェブサーバー)は結果をHTMLファイルだと思い込んでいて、ブラウザにも「HTMLファイルが来る」と伝えてしまう。これは「ヘッダー」というものを使って行われていて、その中でデータの種類が指定されている。これはMIMEタイプと呼ばれるもので、一覧はリンク先で見ることができる。

In今回は、結果がHTMLファイルではなくJSONファイルであることをブラウザに伝えたい。これは、PHPの this case, we want to tell the browser that the result is not an HTML file but a JSON file. We can do so by using the PHP header() instruction:という命令を使うことでできる。

// JSONを返すべき
header("Content-Type: application/json; charset=utf-8");

Change the header on the exercise before and see how it changes the result.

 先ほどの練習でヘッダーを変えてみて、結果がどう変わるか確認してください。