【发布时间】:2011-05-15 10:01:39
【问题描述】:
有没有办法在 Ruby 中将 JSON 转换为 XML?
【问题讨论】:
-
我添加了
activesupport标签并将你的标题变成了一个问题。
标签: ruby xml json activesupport
有没有办法在 Ruby 中将 JSON 转换为 XML?
【问题讨论】:
activesupport标签并将你的标题变成了一个问题。
标签: ruby xml json activesupport
其他答案不允许简单的递归转换。正如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>
【讨论】:
我不知道有什么神奇的方法可以做到这一点,但你可以轻松地做 xml 到 hash 和 hash 到 json。
require 'active_support'
my_hash = Hash.from_xml(my_xml)
然后
require 'json'
my_json = my_hash.to_json
【讨论】:
关于@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。
【讨论】:
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 的根参数。如果您不指定根,它将使用“哈希”一词作为根,这看起来不太好。