Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6079041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T10:54:06+00:00 2026-05-23T10:54:06+00:00

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

  • 0

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 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T10:54:06+00:00Added an answer on May 23, 2026 at 10:54 am

    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:

    require 'nokogiri'
    require 'json'
    class Nokogiri::XML::Node
      def to_json(*a)
        {"$name"=>name}.tap do |h|
          kids = children.to_a
          h.merge!(attributes)
          h.merge!("$text"=>text) unless text.empty?
          h.merge!("$kids"=>kids) unless kids.empty?
        end.to_json(*a)
      end
    end
    class Nokogiri::XML::Document
      def to_json(*a); root.to_json(*a); end
    end
    class Nokogiri::XML::Text
      def to_json(*a); text.to_json(*a); end
    end
    class Nokogiri::XML::Attr
      def to_json(*a); value.to_json(*a); end
    end
    
    xml = Nokogiri::XML '<root a="b" xmlns:z="zzz">
      <z:a>Hello <b z:x="y">World</b>!</z:a>
    </root>'
    puts xml.to_json
    
    {
      "$name":"root",
      "a":"b",
      "$text":"Hello World!",
      "$kids":[
        {
          "$name":"a",
          "$text":"Hello World!",
          "$kids":[
            "Hello ",
            {
              "$name":"b",
              "x":"y",
              "$text":"World",
              "$kids":[
                "World"
              ]
            },
            "!"
          ]
        }
      ]
    }
    

    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:

    require 'nokogiri'
    require 'json'
    class Nokogiri::XML::Node
      def namespaced_name
        "#{namespace && "#{namespace.prefix}:"}#{name}"
      end
    end
    class Nokogiri::XML::Element
      def to_json(*a)
        [namespaced_name].tap do |parts|
          unless attributes.empty?
            parts << Hash[ attribute_nodes.map{ |a| [a.namespaced_name,a.value] } ]
          end
          parts.concat(children.select{|n| n.text? ? (n.text=~/\S/) : n.element? })
        end.to_json(*a)
      end
    end
    class Nokogiri::XML::Document
      def to_json(*a); root.to_json(*a); end
    end
    class Nokogiri::XML::Text
      def to_json(*a); text.to_json(*a); end
    end
    class Nokogiri::XML::Attr
      def to_json(*a); value.to_json(*a); end
    end
    
    xml = Nokogiri::XML '<root a="b" xmlns:z="zzz">
      <z:a>Hello <b z:x="y">World</b>!</z:a>
    </root>'
    puts xml.to_json
    #=> ["root",{"a":"b"},["z:a","Hello ",["b",{"z:x":"y"},"World"],"!"]]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

basically i have parsed some data from XML into a NSMutableArray that is shared
I have a UITableView which is populated with some parsed JSON twitter data. The
I have some JSON parsed, but I would like to take a link I
I have some JSON scripts that I plan on parsing on the site and
I'm retrieving an HTML document that is parsed with Nokogiri. The HTML is using
I use this bit of code to feed some data i have parsed from
I have some data passed into the flex via webservices, and want to create
I have some C code that parses a file and generates another file of
I have some sort of recursive function, but I need to parse a string,
I am trying to parse some XML i have retrieved via e4x in an

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.