xml2json

Code Climate Gem Version Dependency Status Build Status

Transforms XML into JSON

Installation

Add this to your Gemfile

gem 'xml2json', git: '[email protected]:monksoftware/xml2json.git'

Configuration

Attributes, text and namespaces key name can be customized, defaults are _attributes, _text and _namespaces

XML2JSON.config do |c|
    c.attributes_key = "attr"
    c.namespaces_key = "nsp"
    c.text_key = "txt"
end

Usage

XML2JSON.parse(xml_string)         # => this outputs a json string
XML2JSON.parse_to_hash(xml_string) # => this outputs a ruby hash

Examples

Input XML

xml = '<?xml version="1.0" encoding="utf-8"?>
        <root>
            <author><name>Andrea</name><email>[email protected]</email></author>
            <author><name>Giuseppe</name><email>[email protected]</email></author>
        </root>'

Parse to JSON string

XML2JSON.parse(xml)

output is a string

{"root":{"authors":[{"name":"Andrea", "email":"[email protected]"},{"name":"Giuseppe", "email":"[email protected]"}]}}

Parse to Ruby Hash

XML2JSON.parse_to_hash(xml)

output is a hash

{"root" => {"authors" => [{"name" => "Andrea", "email" => "[email protected]"},{"name" => "Giuseppe", "email" => "[email protected]"}]}}