有没有XML转换成JSON在Ruby库?
Answer 1:
一个简单的窍门:
首先,你需要gem install json
使用Rails时,你可以这样做,那么:
require 'json'
require 'active_support/core_ext'
Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}"
如果你不使用Rails,那么你就可以gem install activesupport
,需要它,事情应该工作的顺利开展。
例:
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
Answer 2:
我会用裂纹 ,一个简单的XML和JSON解析器。
require "rubygems"
require "crack"
require "json"
myXML = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
Answer 3:
如果您想保留的所有属性,我建议cobravsmongoose http://cobravsmongoose.rubyforge.org/它采用BadgerFish约定。
<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>
变为:
{"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}}
码:
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
Answer 4:
您可能会发现xml-to-json
宝石是有用的。 它维护属性,处理指令和DTD声明。
安装
gem install 'xml-to-json'
用法
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
生产:
{
"type": "element",
"name": "root",
"attributes": [
{
"type": "attribute",
"name": "some-attr",
"content": "hello",
"line": 1
}
],
"line": 1,
"children": [
{
"type": "text",
"content": "ayy lmao",
"line": 1
}
]
}
这是一个简单的衍生xml-to-hash
。
Answer 5:
假设你正在使用的libxml,你可以试试这个的变化(免责声明,这个工作对我有限的使用情况下,可能需要调整是完全通用)
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
Answer 6:
如果你正在寻找的速度,我会建议牛 ,因为它几乎已经提到的那些最快的选项。
我跑了使用从拥有110 MB的XML文件一些基准omg.org/spec而这些结果(以秒为单位):
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
文章来源: Ruby XML to JSON Converter?