Ruby XML to JSON Converter?

Viewed 47953

Is there a library to convert XML to JSON in Ruby?

7 Answers

If you wish to keep all attributes I recommend cobravsmongoose http://cobravsmongoose.rubyforge.org/ which uses the badgerfish convention.

<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>

becomes:

{"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}}

code:

require 'rubygems'
require 'cobravsmongoose'
require 'json'
xml = '<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>'
puts CobraVsMongoose.xml_to_hash(xml).to_json

Simple but with heavy dependencies (active_support); it's not much of a problem if you already are in a Rails environment.

require 'json'
require 'active_support/core_ext'

Hash.from_xml(xml_string).to_json

Else it would be probably better to use ox or rexml to have much lighter dependencies and more performance.

Related