How can I convert JSON to XML in Ruby?

Mark Szymanski picture Mark Szymanski · Nov 25, 2010 · Viewed 13.4k times · Source

Is there any way to convert JSON to XML in Ruby?

Answer

rwilliams picture rwilliams · Nov 25, 2010
require 'active_support' #for to_xml() 'gem install activesupport' use the 2.3 branch
require 'json' #part of ruby 1.9 but otherwise 'gem install json'

my_json = "{\"test\":\"b\"}"
my_xml = JSON.parse(my_json).to_xml(:root => :my_root)

Also note the root argument of to_xml. If you don't specify a root it'll use the word 'hash' as the root which isn't very nice to look at.