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 :)
This one works for me:
This method is using active support, so if you are not using rails then include active support core extensions manually:
Here's one way to do it. As noted by my comment, the 'right' answer depends on what your output should be. There is no canonical representation of XML nodes in JSON, and hence no such capability is built into the libraries involved:
Note that the above completely ignores namespaces, which may or may not be what you want.
Converting to JsonML
Here's another alternative that converts to JsonML. While this is a lossy conversion (it does not support comment nodes, DTDs, or namespace URLs) and the format is a little bit "goofy" by design (the first child element is at
[1]
or[2]
depending on whether or not attributes are present), it does indicate namespace prefixes for elements and attributes: