LoginSignup
5
5

More than 3 years have passed since last update.

学習メモ JSONの基本とjson_encode / json_decode

Posted at

JSON

JSONとはデータ形式の一つ。
JavaScript Object Notationの略。

データを扱う際、誰が書いても同じであるように、また機械が判別できるように書き方のルールが決まっている。HTMLやCSVなども1つのデータ形式であり、JSONもその一つに含まれる。

JSON形式

{
  "user": "Tom",
  "age" : 18,
  "gender": "male"
}

json_encodeとjson_decode

今、PHPについて学習中だが、PHPではデータをJSON形式に変換したり、JSON形式にデコード(変換されたものから復元)できる。

エンコード:

ある形式のデータを一定の規則に基づいて別の形式のデータ
に変換すること。

デコード

変換されたデータを逆に、復元すること

例:

//配列
menu_array = ['coffee' => 'menu1'
              'tea' => 'menu2'
              'juice' => 'menu3'
             ]

json_encodeでエンコードする

//json形式に変換
$json = json_encode($menu_array);

結果

{"coffee": "menu1", "tea": "menu2", "juice": "menu3"}

json_decodeでデコードする

$menu = json_decode($json, true);

結果

Array ( [coffee] => menu1
        [tea] => menu2
        [juice] => menu3
      )
5
5
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
5
5