Convert XML to JSON with Nokogiri

How XML-to-JSON conversion with Nokogiri works, what it keeps and loses, and when to keep the original XML or plain text instead.

Nokogiri is a Ruby library for parsing XML and HTML. It has no single method that turns an XML document into structured JSON. In practice, converting XML to JSON with Nokogiri takes one of two routes. You can parse with Nokogiri and walk the tree yourself, or you can let a library such as ActiveSupport use Nokogiri as its parsing backend. Both routes work. XML and JSON model data differently, though, so the mapping rules you choose decide whether the result keeps the meaning you need.

Is this conversion suitable for your use?

Conversion is a good fit when the XML holds record-like data, such as configuration, API responses or feeds, and the consumer expects JSON. The main benefit is that the data becomes plain hashes, arrays and strings that JavaScript tools, web APIs and document stores handle natively. The main tradeoff is that the conversion loses information unless you define the mapping deliberately. Attributes, repeated elements, ordering, namespaces, mixed content and data types all need a rule.

Keep the original XML, or share plain text, in these cases:
• The document is prose with inline markup, such as XHTML or DocBook.
• The document is digitally signed. Conversion breaks the signed form.
• A downstream step validates against an XML schema.
• You need an exact round trip back to XML.
• A person only needs to read the content. Pretty-printed XML may already be enough.

What the conversion actually changes

The conversion changes the data model, not just how the data looks. Pretty-printing XML or JSON only adds or removes whitespace between tokens, which is a presentation change. Moving from XML to JSON is different: it rebuilds the tree in a format with fewer concepts. It is not a character transformation like text reversal or Unicode styling. The characters inside text content pass through unchanged unless your code strips, trims or casts them.

XML feature | Gap in JSON | Typical handling
Attributes | No attribute concept | Prefixed keys such as "@id", or merged with child element keys
Repeated sibling elements | No implicit repetition | An array, but a single occurrence often becomes an object, so the output shape varies
Order of differently named siblings | Object member order is not significant under the JSON spec | Lost for many consumers unless you emit an ordered array of nodes
Mixed content (text interleaved with elements) | No direct equivalent | Often dropped or flattened
Namespaces and prefixes | No namespace concept | Dropped, kept as prefixed names, or mapped explicitly
Comments, processing instructions, CDATA markers | Not representable | Usually discarded; CDATA content is kept as an ordinary string
Data types | XML content is text | Strings, unless the converter casts values
Empty elements | No empty-element form | Empty string, null or empty object, depending on the converter

A minimal converter written with Nokogiri

The sketch below follows one common convention. Attributes become keys prefixed with "@". The text of an element that also has attributes goes under "#text". Repeated child names become arrays. Treat it as a starting point, not a complete mapping.

require "nokogiri"
require "json"

def node_to_value(node)
  attrs = node.attribute_nodes.to_h { |attr| ["@#{attr.name}", attr.value] }
  children = node.element_children

  if children.empty?
    text = node.text.strip
    return text if attrs.empty?
    return text.empty? ? attrs : attrs.merge("#text" => text)
  end

  children.each_with_object(attrs) do |child, result|
    value = node_to_value(child)
    if result.key?(child.name)
      result[child.name] = [result[child.name]] unless result[child.name].is_a?(Array)
      result[child.name] << value
    else
      result[child.name] = value
    end
  end
end

doc = Nokogiri::XML(File.read("order.xml")) { |config| config.strict }
root = doc.root
puts JSON.pretty_generate({ root.name => node_to_value(root) })

Given this input:

<order id="42">
  <item sku="A1">Pen</item>
  <item sku="B2">Notebook</item>
  <note/>
</order>

Following the code's logic, the script prints:

{
  "order": {
    "@id": "42",
    "item": [
      {
        "@sku": "A1",
        "#text": "Pen"
      },
      {
        "@sku": "B2",
        "#text": "Notebook"
      }
    ],
    "note": ""
  }
}

This example shows the tradeoffs from the table above:
• The id stays the string "42", not a number.
• If the order had only one item, "item" would be an object instead of an array. Code reading the JSON must handle both shapes, or you can force arrays for known repeating elements.
• The empty note becomes an empty string.
• Leading and trailing whitespace in text is trimmed. That is wrong for content where whitespace matters.
• Text sitting directly between child elements is ignored.
• Nokogiri's name method returns the local name without a namespace prefix. Elements from different namespaces that share a local name will collide under one key.

Using ActiveSupport with Nokogiri as the parser

If your project already uses ActiveSupport, its Hash.from_xml can parse through Nokogiri when you select Nokogiri as the XmlMini backend. The nokogiri gem must be installed.

require "active_support"
require "active_support/core_ext/hash/conversions"
require "json"

ActiveSupport::XmlMini.backend = "Nokogiri"
hash = Hash.from_xml(File.read("order.xml"))
puts JSON.pretty_generate(hash)

This route is shorter, but it applies Rails conventions instead of a neutral mapping:
• Attributes go into the same hash as child elements, with no distinguishing prefix.
• Dashes in names are rewritten as underscores.
• Values with certain type attributes may be cast.
Check the documentation for the ActiveSupport version you use before depending on the exact output shape.

Parsing strictly and safely

By default, Nokogiri tries to recover from malformed XML and records problems in the document's errors list. A broken input can therefore still produce JSON that is missing data. Using strict mode, as in the converter above, makes parsing raise an error instead. When you need to know the input was valid, strict mode or a check of doc.errors is the safer choice. Nokogiri's default parse options also leave entity substitution off and block network access. Do not enable either option for untrusted input.

Will the JSON stay usable after copying or sharing?

  • Encoding: the current JSON specification requires UTF-8 for JSON exchanged between systems. Ruby's JSON generator writes non-ASCII characters as-is by default. If a destination mishandles them, the ascii_only option writes them as escape sequences instead.
  • Quotes and line breaks: word processors and some messaging or email tools can replace straight quotes with curly ones or rewrap long lines, and either change makes JSON invalid. Sharing a file or a code block avoids this, and running JSON.parse on the pasted result confirms it survived.
  • Readability: pretty_generate suits human review, and generate suits compact transport. The whitespace difference does not change the data.
  • Search and editing: keys such as "@sku" and "#text" are conventions of this converter, not part of either format. Anyone querying or editing the JSON needs to know the mapping, so document it alongside the data.
  • Accessibility: no documentation or test results were available on how screen readers or other assistive technology present deeply nested JSON. When a person rather than a program will read the content, provide a plain-text summary or keep a readable original.

Gaps in this review

No benchmarks, version-specific test results or measured performance figures were available. The behavior described here comes from the documented conventions of Nokogiri, ActiveSupport and Ruby's JSON library, so verify it against the versions you install. The examples load the whole document into memory. Very large files may call for Nokogiri's streaming interfaces (SAX and Reader), which this review does not cover.