How to convert Nokogiri Document object into JSON

berkes picture berkes · Jun 25, 2011 · Viewed 12.6k times · Source

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 :)

Answer

odiszapc picture odiszapc · May 29, 2012

This one works for me:

Hash.from_xml(@nokogiri_object.to_xml).to_json

This method is using active support, so if you are not using rails then include active support core extensions manually:

require 'active_support/core_ext/hash'