如何在Ruby中将JSON转换为XML?
有没有办法在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’这个词作为root,这看起来不是很好。
关于@rwilliams又名r-dub答案:
ActiveSupport将其组件移动到单独的模块中以实现粒度。 我们可以告诉它只加载某些子集,或者,如果我们仍然选择,我们可以一次加载所有内容,而不是一次性加载所有内容。 无论如何,我们不能像require 'activesupport'
那样使用require 'activesupport'
,而是我们必须使用require 'activesupport/all'
或其中一个子集。
>> require 'active_support/core_ext/array/conversions' #=> true >> [{:a => 1, :b => 2}, {:c => 3}].to_xml => "\n\n \n \n \n"
此外,ActiveSupport包含JSON支持,因此您可以使用AR完成整个转换:
>> require 'active_support/all' #=> true >> json = {'foo'=>'bar'}.to_json #=> "{"foo":"bar"}" >> ActiveSupport::JSON.decode(json).to_xml #=> "\n\n bar \n \n"
第一行加载XML和JSON转换。 第二行设置JSON样本以用于测试。 第三行采用假装JSON,对其进行解码,然后将其转换为XML。
其他答案不允许简单的递归转换。 正如在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' } ] } ] }, ]
……进入这个:
category1 subCategory1 productName1 desc1 productName2 desc2 category2 subCategory2.1 productName2.1.1 desc1 productName2.1.2 desc2
我不知道这是一个神奇的gem,但你可以轻松做的是xml哈希和哈希到json。
require 'active_support' my_hash = Hash.from_xml(my_xml)
然后
require 'json' my_json = my_hash.to_json
- ActiveSupport中mattr_accessor和cattr_accessor之间的区别?
- NoMethodError:ActiveSupport的未定义方法`halt_callback_chains_on_return_false =’:模块
- rails 3.1变形问题
- Rails:在时区中获取#beginning_of_day
- Rails time_ago_in_words产生错误的输出
- 未初始化的常量TZInfo :: InvalidTimezoneIdentifier(NameError) – Rails 4
- Ruby没有找到新版本的OpenSSL
- 在Rails 4.1中,validates_inclusion_of不再一样吗?
- rails activesupport通知 – 错误的db运行时值