How to convert Nokogiri Document object into JSON

Viewed 13932

I have some parsed Nokogiri::XML::Document objects that I want to print as JSON.

I can go the route of making it a string, parsing it into a hash, with active-record or Crack and then Hash.to_json; but that is both ugly and depending on way too manay libraries.

Is there not a simpler way?

As per request in the comment, for example the XML <root a="b"><a>b</a></root> could be represented as JSON:

<root a="b"><a>b</a></root> #=> {"root":{"a":"b"}}
<root foo="bar"><a>b</a></root> #=> {"root":{"a":"b","foo":"bar"}}

That is what I get with Crack now too. And, sure, collisions between entities and child-tags are a potential problem, but I build most of the XML myself, so it is easiest for me to avoid these collisions alltogether :)

3 Answers

If you are trying to convert a SOAP request to REST, this one works too:

require 'active_support/core_ext/hash'
require 'nokogiri'

xml_string = "<root a=\"b\"><a>b</a></root>"
doc = Nokogiri::XML(xml_string)
Hash.from_xml(doc.to_s)
Related