Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

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

やりたいこと

次の 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:

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?