あまブログ

ドキドキ......ドキドキ2択クイ〜〜〜〜〜〜〜ズ!!

RubyでJSONファイルを扱う方法

この記事ではJSONの基礎と、RubyJSONファイルを扱う方法を紹介します。

1. JSONの基礎

1-1. JSON(JavaScript Object Notation)とは

1-2. JSONの表記方法

JSONのデータ型

JSONは以下のデータ型で構成されます。

  1. 文字列(string)
  2. 数値(number)
  3. 真偽値(boolean)
  4. ヌル値(null)
  5. オブジェクト(object)
  6. 配列(array)
1. 文字列(string)
{"name":"John"}
  • ダブルクォーテーションで囲んだ文字列を指定(シングルクォーテーションは使えない)
  • バックスラッシュでエスケープしたUnicode文字で構成される
2. 数値(number)
{
  "number_1" : 210,
  "number_2" : 215,
  "number_3" : 21.05,
  "number_4" : 10.05
}
  • 10進法表記のみ(8進、16進法表記は使えない)
  • 浮動小数点数も使用できる
3. 真偽値(boolean)
{
  "active_flag": true,
  "delete_flag": false
}
  • truefalseはすべて小文字で指定
4. ヌル値(null)
{"middlename":null}
  • nullはすべて小文字で指定
5. オブジェクト(object)
{
  "employee":{
    "name":"John",
    "age":30,
    "city":"New York"
  }
}
6. 配列(array)
[
  {
    "name":"John",
    "age":30
  },
  {
    "name":"Carol",
    "age":21
  }
]
  • 配列要素には、文字列、数値、真偽値、ヌル値、オブジェクト、配列すべてを使用できる

2. RubyJSONファイルを扱う方法

2-1. JSONファイルを読み込んでRubyオブジェクトに変換する

array.json

["apple","orange"]

上記のarray.jsonファイルを読み込んでRubyの配列オブジェクトに変換します。

require 'json'

array = File.open('array.json') { |file| JSON.load(file) }

p array #=> ["apple", "orange"]

object.json

{
  "employee": {
    "name": "Molecule Man",
    "age": 29
  }
}

上記のobject.jsonファイルを読み込んでRubyのハッシュオブジェクトに変換します。

require 'json'

hash = File.open('object.json') { |file| JSON.load(file) }

p hash #=> {"employee"=>{"name"=>"Molecule Man", "age"=>29}}

ama-tech.hatenablog.com

2-2. RubyオブジェクトをJSONファイルへ書き込む

Rubyの配列オブジェクトをsample1.jsonファイルに書き込みます。

require 'json'

array = ["apple","orange"]

File.open("sample1.json", 'w') { |file| JSON.dump(array, file) }

sample1.json

["apple","orange"]

Rubyのハッシュオブジェクトをsample2.jsonファイルに書き込みます。

require 'json'

hash = { "Ocean" => { "Squid" => 10, "Octopus" =>8 }}

File.open("sample2.json", 'w') { |file| JSON.dump(hash, file) }

sample2.json

{"Ocean":{"Squid":10,"Octopus":8}}

【参考】