有没有办法在Ruby中将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的root参数。如果您不指定根,则会使用“hash”作为根,这看起来不太好。
active_support
的 gem 吗?当我尝试 require
它时,出现了一个错误。 - Mark Szymanski关于@rwilliams,也就是r-dub的回答:
ActiveSupport将其组件移入单独的模块以实现粒度控制。我们可以告诉它仅加载特定子集,或者如果仍然选择这样做,我们可以一次性加载所有内容。无论如何,我们不能像以前那样使用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"
>> 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"
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转换为哈希,再将哈希转换为JSON。
require 'active_support'
my_hash = Hash.from_xml(my_xml)
然后
require 'json'
my_json = my_hash.to_json
activesupport
标签,并将您的标题改成了一个问题。 - the Tin Man