Convert between XML, Hash, YAML, JSON in Ruby - Conversion Cheat Sheet
Ruby, Uncategorized No Comments »Here’s a little XML/JSON/YAML/Hash conversion cheat sheet for Ruby:
First, let’s create an XML document:
require ‘rubygems’
require ‘nokogiri’
builder = Nokogiri::XML::Builder.new do |xml|
xml.root {xml.products {xml.widget {xml.id_ “10″xml.name “Awesome widget”}}}endmy_xml = builder.to_xml
XML To Hash:
require ‘active_support’ #if you have Rails installed
my_hash = Hash.from_xml(my_xml)
Withou Rails/ActiveSupport, have a look at Crack which very fast and will usually give you enough fields (it eats attributes however):
my_hash = Crack::XML.parse(my_xml)
Hash To Object?
Have a look here: http://blog.jayfields.com/2008/01/ruby-hashtomod.html
Hash To JSON:
require ‘json’
my_json = my_hash.to_json
JSON back to Hash:
my_hash = JSON.parse(my_json)
Also have a look at Crack:
my_hash = Crack::JSON.parse(my_json)
Hash To YAML:
my_yaml = my_hash.to_yaml
YAML back to Hash:
my_hash = YAML::load(my_yaml)
Bonus Points – Hash to XML:
require ‘xmlsimple’
my_xml = XmlSimple.xml_out(my_hash, {’KeepRoot’ => true})
There is currently no way to preserve the attributes (like <person age=”10″>Joe</person>) with such conversion from Hash to XML.

Recent Comments