Data Formats
34.1 JSON
Faster alternatives: Oj. Ruby 3.4's built-in json gem got much faster.
require "json"
data = { name: "Ana", tags: ["admin"], active: true, score: nil }
json = data.to_json # or JSON.generate(data)
pretty = JSON.pretty_generate(data)
parsed = JSON.parse(json) # string keys
sym = JSON.parse(json, symbolize_names: true)
JSON.load_file("config.json")
File.write("out.json", JSON.pretty_generate(data))
class User
def initialize(name) = @name = name
def to_h = { name: @name }
def to_json(*args) = to_h.to_json(*args)
end
[User.new("Bo")].to_json34.2 YAML
require "yaml"
config = YAML.load_file("config.yml", symbolize_names: true) # safe by default in Psych 4 (Ruby 3.1+)
YAML.safe_load(str, permitted_classes: [Date]) # explicit safe loading
YAML.unsafe_load(str) # ⚠️ only for trusted input
puts({ "db" => { "port" => 5432 } }.to_yaml)34.3 CSV
require "csv" # a bundled gem since Ruby 3.4 (add it to your Gemfile)
CSV.foreach("users.csv", headers: true, header_converters: :symbol) do |row|
puts "#{row[:name]} - #{row[:email]}"
end
table = CSV.read("users.csv", headers: true)
table.map { it["name"] }
CSV.open("out.csv", "w") do |csv|
csv << %w[name score]
csv << ["Ana", 95]
end
CSV.parse("a,b\n1,2", headers: true).map(&:to_h)
CSV.generate { |csv| csv << [1, 2] }34.4 XML, Marshal and Others
Others: MessagePack (msgpack), Protocol Buffers (google-protobuf), TOML (tomlrb), ox, Base64 (require "base64" is a bundled gem in 3.4; [str].pack("m0") is the core equivalent).
require "rexml/document" # bundled gem; Nokogiri is the popular, fast alternative
doc = REXML::Document.new(File.read("books.xml"))
doc.elements.each("library/book/title") { puts it.text }
# Nokogiri
# doc = Nokogiri::XML(xml); doc.css("book title").map(&:text); Nokogiri::HTML(html).at_css("h1")&.text
bytes = Marshal.dump(obj) # Ruby-specific binary serialization
copy = Marshal.load(bytes) # ⚠️ NEVER load untrusted data (remote code execution risk)