0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

データ yaml json

Last updated at Posted at 2019-10-09

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?