yaml
- 構造化したデータを表現するモノ
記事
基本
require 'yaml'
yaml_data = <<-DATA
- RED
- GREEN
- BLU
DATA
YAML.load(yaml_data)
# リテラル
yaml_data = <<-DATA
- RED
- GREEN
- BLU
DATA
p YAML.load(yaml_data)
# リテラル出力
➜ Desktop ruby sample.rb
["RED", "GREEN", "BLU"]
"\ndefault: &default\n adapter: mysql2\n host: 127.0.0.1\n encoding: utf8\n pool: 5\n username: root\n password:\n reconnect: false\n\ndevelopment:\n <<: *default\n database: development\n\ntest:\n <<: *default\n database: test\n\n\n"
#yml形式
database = <<-DATA
default: &default
adapter: mysql2
host: 127.0.0.1
encoding: utf8
pool: 5
username: root
password:
reconnect: false
development:
<<: *default
database: development
test:
<<: *default
database: test
DATA
p YAML.load(database)
#yml形式 出力
➜ Desktop ruby sample.rb
["RED", "GREEN", "BLU"]
{"default"=>{"adapter"=>"mysql2", "host"=>"127.0.0.1", "encoding"=>"utf8", "pool"=>5, "username"=>"root", "password"=>nil, "reconnect"=>false}, "development"=>{"adapter"=>"mysql2", "host"=>"127.0.0.1", "encoding"=>"utf8", "pool"=>5, "username"=>"root", "password"=>nil, "reconnect"=>false, "database"=>"development"}, "test"=>{"adapter"=>"mysql2", "host"=>"127.0.0.1", "encoding"=>"utf8", "pool"=>5, "username"=>"root", "password"=>nil, "reconnect"=>false, "database"=>"test"}}
json
- json(JavaScript Object Notation)とは
javascriptのオブジェクト
require 'json'
yaml_data = <<-DATA
["Red","Blue","Red"]
DATA
JSON.load(yaml_data)
# json は基本はオブジェクト
example.json
{
"ruby": {
"rails":30000
},
"python": {
"django":25000
}
}
require 'json'
File.open("example.json") do |file|
hash = JSON.load(file)
p hash
end
hash = JSON.parse('{"ruby":{"rails":30000},"python":{"django":25000}}')
p hash
{"ruby"=>{"rails"=>30000}, "python"=>{"django"=>25000}}
# 文字列型のjsonもある
- parse
hash = JSON.parse('{"ruby":{"rails":30000},"python":{"django":25000}}')
p hash
{"ruby"=>{"rails"=>30000}, "python"=>{"django"=>25000}}
- json 作成
generate
ハッシュ → jsonに
require 'json'
hash = JSON.generate({"ruby":{"rails":30000},"python":{"django":25000}})
p hash
to_json
# ruby で用意してくれている
require 'json'
hash = {"ruby":{"rails":30000},"python":{"django":25000}}.to_json
p hash