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
2009-10-07 09:32:22
sick man, thanks!
viatropos
2009-10-07 11:57:32
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
2010-08-17 17:34:23