如何在 Ruby 中将 JSON 转换为 XML?
Posted
技术标签:
【中文标题】如何在 Ruby 中将 JSON 转换为 XML?【英文标题】:How can I convert JSON to XML in Ruby? 【发布时间】:2011-05-15 10:01:39 【问题描述】:有没有办法在 Ruby 中将 JSON 转换为 XML?
【问题讨论】:
我添加了activesupport
标签并将你的标题变成了一个问题。
【参考方案1】:
其他答案不允许简单的递归转换。正如this answer on Code Review 中所述,您需要一个自定义助手来创建您正在寻找的简单格式。
它会变成这样...
data = [
'name' => 'category1',
'subCategory' => [
'name' => 'subCategory1',
'product' => [
'name' => 'productName1',
'desc' => 'desc1' ,
'name' => 'productName2',
'desc' => 'desc2' ]
]
,
'name' => 'category2',
'subCategory' => [
'name' => 'subCategory2.1',
'product' => [
'name' => 'productName2.1.1',
'desc' => 'desc1' ,
'name' => 'productName2.1.2',
'desc' => 'desc2' ]
]
,
]
...进入这个:
<?xml version="1.0"?>
<root>
<category>
<name>category1</name>
<subCategory>
<name>subCategory1</name>
<product>
<name>productName1</name>
<desc>desc1</desc>
</product>
<product>
<name>productName2</name>
<desc>desc2</desc>
</product>
</subCategory>
</category>
<category>
<name>category2</name>
<subCategory>
<name>subCategory2.1</name>
<product>
<name>productName2.1.1</name>
<desc>desc1</desc>
</product>
<product>
<name>productName2.1.2</name>
<desc>desc2</desc>
</product>
</subCategory>
</category>
</root>
【讨论】:
【参考方案2】:我不知道有什么神奇的方法可以做到这一点,但你可以轻松地做 xml 到 hash 和 hash 到 json。
require 'active_support'
my_hash = Hash.from_xml(my_xml)
然后
require 'json'
my_json = my_hash.to_json
【讨论】:
我正在尝试将 JSON 转换为 XML,而不是 XML 转换为 JSON 那些奇怪的引用会起作用吗?这看起来不太健康。 @elusive:是的,它们在我看来也很时髦。我认为它们是聪明的引语。【参考方案3】:关于@rwilliams aka r-dub 答案:
ActiveSupport moved its components 为粒度划分为单独的模块。我们可以告诉它只加载某些子集,而不是一次加载所有内容,或者,如果我们仍然选择,我们可以一次加载所有内容。无论如何,我们不能像以前那样使用require 'activesupport'
,而是必须使用require 'activesupport/all'
或其中一个子集。
>> require 'active_support/core_ext/array/conversions' #=> true
>> [:a => 1, :b => 2, :c => 3].to_xml
=> "<?xml version="1.0" encoding="UTF-8"?>\n<objects type="array">\n <objects a="1" b="2" type="hash"/>\n <objects c="3" type="hash"/>\n</objects>\n"
此外,ActiveSupport 包含 JSON 支持,因此您可以使用 AR 进行整个转换:
>> require 'active_support/all' #=> true
>> json = 'foo'=>'bar'.to_json #=> ""foo":"bar""
>> ActiveSupport::JSON.decode(json).to_xml #=> "<?xml version="1.0" encoding="UTF-8"?>\n<hash>\n <foo>bar</foo>\n</hash>\n"
第一行加载 XML 和 JSON 转换。第二行设置一个用于测试的 JSON 样本。第三行采用假装的 JSON,对其进行解码,然后将其转换为 XML。
【讨论】:
【参考方案4】:require 'active_support' #for to_xml() 'gem install activesupport' use the 2.3 branch
require 'json' #part of ruby 1.9 but otherwise 'gem install json'
my_json = "\"test\":\"b\""
my_xml = JSON.parse(my_json).to_xml(:root => :my_root)
还要注意 to_xml 的根参数。如果您不指定根,它将使用“哈希”一词作为根,这看起来不太好。
【讨论】:
active_support
需要一些宝石吗?我在尝试 require
时遇到错误。
是的。主动支持是 Ruby on Rails 的一部分。您应该可以使用“gem install activesupport”安装它
现在每当我尝试运行它时,我都会收到以下错误:undefined method
to_xml' for #<0x1013b2b60>
0x1013b2b60>
以上是关于如何在 Ruby 中将 JSON 转换为 XML?的主要内容,如果未能解决你的问题,请参考以下文章