Every once in a while, I need to parse data and import it into Ruby.

Sometimes, the files are in json format, sometimes they are in yaml format, and sometimes they are ruby hashes saved into a file.

I found these ways of parsing the different types of files

JSON file

Input file:

{
  "name": "Alice",
  "age": 30,
  "skills": ["Ruby", "Python"]
}

Ruby Program to parse this

require 'json'
begin
  file_content = File.read("data.json")
  
  # Read entire file as string 
  data_hash = JSON.parse(file_content) 
  
  # Convert JSON string to Ruby Hash 
  puts data_hash.inspect 

rescue Errno::ENOENT
  puts "Error: File not found." 

rescue JSON::ParserError
  puts "Error: Invalid JSON format."
end

YAML file

Input file:

name: Alice
age: 30
skills:
  - Ruby
  - Python

Ruby Program to parse this

require 'yaml'

begin
  data_hash = YAML.load_file("data.yml") # Directly loads YAML into a Ruby Hash
  puts data_hash.inspect
rescue Errno::ENOENT
  puts "Error: File not found."
rescue Psych::SyntaxError
  puts "Error: Invalid YAML format."
end

Ruby literal hash

Input file:

{ 
  name => "Alice",
  age => 30,
  skills => [
    "Ruby", 
    "Python"
  ]
}

Ruby Program to parse this

require 'json'

begin
  # Convert Ruby hash literal to JSON-like string safely
  ruby_hash_string = File.read("data.rb")
  
  # Replace Ruby symbols with JSON keys
  json_like = ruby_hash_string.gsub(/:(\w+)\s*=>?/, '"\1":')
  data_hash = JSON.parse(json_like)

  puts data_hash.inspect
rescue Errno::ENOENT
  puts "Error: File not found."
rescue JSON::ParserError
  puts "Error: Could not parse Ruby hash format."
end