Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

やりたいこと

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

参考

QUANON
あんた、マジなんだな?
http://quanon.github.io/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした