是否有一个库可以在 Ruby 中将 XML 转换为 JSON?
问问题
46523 次
7 回答
108
一个简单的技巧:
首先你需要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
于 2009-10-07T09:32:22.503 回答
25
我会使用Crack,一个简单的 XML 和 JSON 解析器。
require "rubygems"
require "crack"
require "json"
myXML = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
于 2010-10-01T04:17:28.273 回答
13
如果您希望保留所有属性,我推荐使用 badgerfish 约定的 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
于 2011-01-27T17:32:50.310 回答
5
您可能会发现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
。
于 2015-06-14T19:09:30.107 回答
4
如果您正在寻找速度,我会推荐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
于 2017-05-10T13:26:07.867 回答
2
假设您使用的是 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
于 2011-02-22T15:35:34.373 回答
2
简单但有重度依赖(active_support
);如果您已经在 Rails 环境中,这不是什么大问题。
require 'json'
require 'active_support/core_ext'
Hash.from_xml(xml_string).to_json
否则,使用ox
或rexml
拥有更轻的依赖关系和更高的性能可能会更好。
于 2019-12-04T23:58:50.910 回答