Ruby XML para conversor JSON?
Existe uma biblioteca para converter XML para JSON em Ruby?
6 answers
Um simples truque:
Primeiro tens de gem install json
, depois ao usar Carris podes fazer:
require 'json'
require 'active_support/core_ext'
Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}"
Se não estiver a usar Carris, então pode gem install activesupport
, requerê-lo e as coisas devem funcionar sem problemas.
Exemplo:
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
Eu usariaCrack , um simples XML e json parser.
require "rubygems"
require "crack"
require "json"
myXML = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
Se queres manter todos os atributos, recomendo cobravsmongoose http://cobravsmongoose.rubyforge.org/ que usa a Convenção de badgerfish.
<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>
Torna-se:
{"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}}
Código:
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
Pode encontrar o xml-to-json
gem útil. Ele mantém atributos, instrução de processamento e declarações DTD.
Instalar
gem install 'xml-to-json'
Utilização
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
Produz:
{
"type": "element",
"name": "root",
"attributes": [
{
"type": "attribute",
"name": "some-attr",
"content": "hello",
"line": 1
}
],
"line": 1,
"children": [
{
"type": "text",
"content": "ayy lmao",
"line": 1
}
]
}
É uma simples derivação de xml-to-hash
.
Assumindo que está a usar a libxml, pode tentar uma variação disto (disclaimer, isto funciona para o meu caso de uso limitado, pode precisar de ajuste para ser totalmente Genérico)
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
Corri alguns parâmetros de referência usando um ficheiro XML que tem 1, 1 MB de omg.org/spec e estes são os resultados(em segundos):
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