10

有没有办法在 Ruby 中将 JSON 转换为 XML?

4

4 回答 4

12
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 的根参数。如果您不指定根,它将使用“哈希”一词作为根,这看起来不太好。

于 2010-11-24T23:25:29.447 回答
8

关于@rwilliams aka 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"

此外,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。

于 2010-11-25T02:41:57.150 回答
2

其他答案不允许简单的递归转换。正如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>
于 2015-01-14T18:45:38.870 回答
-1

我不知道一个神奇的宝石来做到这一点,但你可以轻松地做的是 xml 散列和散列到 json。

require 'active_support'
my_hash = Hash.from_xml(my_xml)

然后

require 'json'
my_json = my_hash.to_json
于 2010-11-24T23:20:43.997 回答