views:

1259

answers:

2

Is there a library to convert xml to json in ruby?

+8  A: 

A simple trick:

First you need to gem install json, then when using Rails you can do:

require 'json'
Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}"

If you are not using Rails, then you can gem install activesupport, require it and things should work smoothly.

Example:

require 'json'
require 'net/http'
s = Net::HTTP.get_response(URI.parse('http://stackoverflow.com/feeds/tag/ruby/')).body
Hash.from_xml(s).to_json
khelll
sick man, thanks!
viatropos
Sometimes it is important to keep the XML attributes as well. For example, in your example above, "product_code" was lost. What library or libraries would you suggest to keep the attributes?
David James
A: 

I'd use Crack, a simple XML and JSON parser.

require "rubygems"
require "crack"
require "json"

myXML  = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
neilfws