RubyでJSONを扱う基本的な機能を紹介するデモプログラムです。
- JSON文字列をRubyのハッシュに変換
- JSONファイルの読み込みとパース
- JSONのキーをシンボルに変換
- 基本的なエラー処理
- Rubyがインストールされていることを確認
data.jsonファイルを以下のような内容で作成:
{
"name": "佐藤",
"age": 30,
"hobbies": ["読書", "旅行", "プログラミング"]
}- デモを実行:
ruby main.rbrequire 'json'
# JSON文字列をパース
json_string = '{"name": "田中", "age": 25}'
result = JSON.parse(json_string)
# JSONファイルをパース
if File.exist?("data.json")
File.open("data.json") do |file|
data = JSON.parse(file.read)
# データを処理
end
end- Ruby(最新の安定版推奨)
- JSONライブラリ(Ruby標準ライブラリに含まれています)
MIT