[英]Ruby XML to JSON Converter?
是否有一个库可以在 Ruby 中将 XML 转换为 JSON?
一个简单的技巧:
首先你需要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 它,事情应该会顺利进行。
例子:
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
我会使用Crack ,一个简单的 XML 和 JSON 解析器。
require "rubygems"
require "crack"
require "json"
myXML = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
如果您希望保留所有属性,我建议使用 cobravsmongoose http://cobravsmongoose.rubyforge.org/它使用獾约定。
<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
您可能会发现xml-to-json
gem很有用。 它维护属性、处理指令和 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
的简单衍生物。
如果您正在寻找速度,我会推荐Ox,因为它几乎是已经提到的最快的选择。
我使用来自omg.org/spec 的1.1 MB 的 XML 文件运行了一些基准测试,这些是结果(以秒为单位):
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
假设您使用的是 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
简单但依赖重( active_support
); 如果您已经在 Rails 环境中,这不是什么大问题。
require 'json'
require 'active_support/core_ext'
Hash.from_xml(xml_string).to_json
否则,使用ox
或rexml
可能会更好,以获得更轻的依赖项和更高的性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.