LoginSignup
4
1

More than 5 years have passed since last update.

YAML を読みやすい JSON に変換する Ruby スクリプト

Last updated at Posted at 2018-10-30

やりたいこと

次の YAML を JSON に変換したい。

girls.yml
- name: 中川夏紀
  musical_instrument: ユーフォニアム
- name: 吉川優子
  musical_instrument: トランペット
- name: 鎧塚みぞれ
  musical_instrument: オーボエ
- name: 傘木希美
  musical_instrument: フルート

方法

yaml_to_json.rb
require 'json'
require 'yaml'

filepath = ARGV[0]

yaml = File.read(filepath)
obj = YAML.safe_load(yaml, [], [], true)

puts(JSON.pretty_generate(obj))
$ ruby yaml_to_json.rb girls.yml

[
  {
    "name": "中川夏紀",
    "musical_instrument": "ユーフォニアム"
  },
  {
    "name": "吉川優子",
    "musical_instrument": "トランペット"
  },
  {
    "name": "鎧塚みぞれ",
    "musical_instrument": "オーボエ"
  },
  {
    "name": "傘木希美",
    "musical_instrument": "フルート"
  }
]

JSON モジュールに JSON.pretty_generate なんて素敵なメソッドがあるとは :heart_eyes:

参考

4
1
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
4
1