Konwerter Ruby XML do JSON?

Czy istnieje biblioteka do konwersji XML na JSON w Ruby?

Author: the Tin Man, 2009-10-07

6 answers

Prosty trik:

Najpierw musisz gem install json, potem używając Rails możesz zrobić:

require 'json'
require 'active_support/core_ext'
Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}"

Jeśli nie używasz Rails, możesz gem install activesupport, wymagać go i wszystko powinno działać płynnie.

Przykład:

require 'json'
require 'net/http'
require 'active_support/core_ext/hash'
s = Net::HTTP.get_response(URI.parse('https://stackoverflow.com/feeds/tag/ruby/')).body
puts Hash.from_xml(s).to_json
 91
Author: khelll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-29 11:20:29

Użyłbym cracka , prostego parsera XML i JSON.

require "rubygems"
require "crack"
require "json"

myXML  = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
 23
Author: neilfws,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-01 04:17:28

Jeśli chcesz zachować wszystkie atrybuty polecam cobravsmongoose http://cobravsmongoose.rubyforge.org/ który wykorzystuje konwencję borsuków.

<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>

Staje się:

{"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}}

Kod:

require 'rubygems'
require 'cobravsmongoose'
require 'json'
xml = '<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>'
puts CobraVsMongoose.xml_to_hash(xml).to_json
 11
Author: Corban Brook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-27 17:32:50

Możesz znaleźć xml-to-json gem przydatne. Zachowuje atrybuty, instrukcje przetwarzania i instrukcje DTD.

Install

gem install 'xml-to-json'

Użycie

require 'xml/to/json'
xml = Nokogiri::XML '<root some-attr="hello">ayy lmao</root>'
puts JSON.pretty_generate(xml.root) # Use `xml` instead of `xml.root` for information about the document, like DTD and stuff

Produkuje:

{
  "type": "element",
  "name": "root",
  "attributes": [
    {
      "type": "attribute",
      "name": "some-attr",
      "content": "hello",
      "line": 1
    }
  ],
  "line": 1,
  "children": [
    {
      "type": "text",
      "content": "ayy lmao",
      "line": 1
    }
  ]
}

Jest prostą pochodną xml-to-hash.

 4
Author: Maarten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-14 19:09:30

Zakładając, że używasz libxml, możesz wypróbować jego odmianę (Zastrzeżenie, to działa w moim ograniczonym przypadku użycia, może wymagać poprawienia, aby być w pełni ogólnym)

require 'xml/libxml'

def jasonized
  jsonDoc = xml_to_hash(@doc.root)
  render :json => jsonDoc
end

def xml_to_hash(xml)
  hashed = Hash.new
  nodes = Array.new

  hashed[xml.name+"_attributes"] = xml.attributes.to_h if xml.attributes?
  xml.each_element { |n| 
    h = xml_to_hash(n)
    if h.length > 0 then 
      nodes << h 
    else
      hashed[n.name] = n.content
    end
  }
  hashed[xml.name] = nodes if nodes.length > 0
  return hashed
end
 2
Author: erwin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-22 15:35:34

Jeśli szukasz prędkości polecam Ox ponieważ jest to najszybsza opcja z tych już wymienionych.

Uruchomiłem kilka benchmarków używając pliku XML, który ma 1,1 MB z omg.org/spec a oto wyniki (w sekundach):

xml = File.read('path_to_file')
Ox.parse(xml).to_json                    --> @real=44.400012533
Crack::XML.parse(xml).to_json            --> @real=65.595127166
CobraVsMongoose.xml_to_hash(xml).to_json --> @real=112.003612029
Hash.from_xml(xml).to_json               --> @real=442.474890548
 1
Author: Dan F.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-10 13:26:07