Ruby XML 到 JSON 转换器?

发布于 2024-08-07 20:30:34 字数 36 浏览 3 评论 0原文

Ruby 中有一个库可以将 XML 转换为 JSON 吗?

Is there a library to convert XML to JSON in Ruby?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

半﹌身腐败 2024-08-14 20:30:34

一个简单的技巧:

首先你需要gem install json,然后在使用Rails时你可以这样做:

require 'json'
require 'active_support/core_ext'
Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}"

如果你没有使用Rails,那么你可以gem install activesupport,需要它事情应该进展顺利。

示例:

require 'json'
require 'net/http'
require 'active_support/core_ext/hash'
s = Net::HTTP.get_response(URI.parse('https://stackoverflow.com/feeds/tag/ruby/')).body
puts Hash.from_xml(s).to_json

A simple trick:

First you need to gem install json, then when using Rails you can do:

require 'json'
require 'active_support/core_ext'
Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}"

If you are not using Rails, then you can gem install activesupport, require it and things should work smoothly.

Example:

require 'json'
require 'net/http'
require 'active_support/core_ext/hash'
s = Net::HTTP.get_response(URI.parse('https://stackoverflow.com/feeds/tag/ruby/')).body
puts Hash.from_xml(s).to_json
提笔落墨 2024-08-14 20:30:34

我会使用 Crack,一个简单的 XML 和 JSON 解析器。

require "rubygems"
require "crack"
require "json"

myXML  = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json

I'd use Crack, a simple XML and JSON parser.

require "rubygems"
require "crack"
require "json"

myXML  = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
幸福丶如此 2024-08-14 20:30:34

如果您想保留所有属性,我推荐 cobravsmongoose http://cobravsmongoose.rubyforge.org/
它使用獾鱼约定。

<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>

变为:

{"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}}

代码:

require 'rubygems'
require 'cobravsmongoose'
require 'json'
xml = '<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>'
puts CobraVsMongoose.xml_to_hash(xml).to_json

If you wish to keep all attributes I recommend cobravsmongoose http://cobravsmongoose.rubyforge.org/
which uses the badgerfish convention.

<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>

becomes:

{"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}}

code:

require 'rubygems'
require 'cobravsmongoose'
require 'json'
xml = '<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>'
puts CobraVsMongoose.xml_to_hash(xml).to_json
回心转意 2024-08-14 20:30:34

您可能会找到 xml-to-json gem有用。它维护属性、处理指令和DTD 语句。

安装

gem install 'xml-to-json'

使用

require 'xml/to/json'
xml = Nokogiri::XML '<root some-attr="hello">ayy lmao</root>'
puts JSON.pretty_generate(xml.root) # Use `xml` instead of `xml.root` for information about the document, like DTD and stuff

产生:

{
  "type": "element",
  "name": "root",
  "attributes": [
    {
      "type": "attribute",
      "name": "some-attr",
      "content": "hello",
      "line": 1
    }
  ],
  "line": 1,
  "children": [
    {
      "type": "text",
      "content": "ayy lmao",
      "line": 1
    }
  ]
}

它是 xml-to-hash 的简单衍生品

You may find the xml-to-json gem useful. It maintains attributes, processing instruction and DTD statements.

Install

gem install 'xml-to-json'

Usage

require 'xml/to/json'
xml = Nokogiri::XML '<root some-attr="hello">ayy lmao</root>'
puts JSON.pretty_generate(xml.root) # Use `xml` instead of `xml.root` for information about the document, like DTD and stuff

Produces:

{
  "type": "element",
  "name": "root",
  "attributes": [
    {
      "type": "attribute",
      "name": "some-attr",
      "content": "hello",
      "line": 1
    }
  ],
  "line": 1,
  "children": [
    {
      "type": "text",
      "content": "ayy lmao",
      "line": 1
    }
  ]
}

It's a simple derivative of xml-to-hash.

走过海棠暮 2024-08-14 20:30:34

如果您正在寻找速度,我会推荐 Ox 因为它几乎是现有选项中最快的选项提及。

我使用 omg.org/spec
这些是结果(以秒为单位):

xml = File.read('path_to_file')
Ox.parse(xml).to_json                    --> @real=44.400012533
Crack::XML.parse(xml).to_json            --> @real=65.595127166
CobraVsMongoose.xml_to_hash(xml).to_json --> @real=112.003612029
Hash.from_xml(xml).to_json               --> @real=442.474890548

If you're looking for speed I would recommend Ox since it's pretty much the fastest option from the ones already mentioned.

I ran some benchmarks using an XML file that has 1.1 MB from omg.org/spec
and these are the results(in seconds):

xml = File.read('path_to_file')
Ox.parse(xml).to_json                    --> @real=44.400012533
Crack::XML.parse(xml).to_json            --> @real=65.595127166
CobraVsMongoose.xml_to_hash(xml).to_json --> @real=112.003612029
Hash.from_xml(xml).to_json               --> @real=442.474890548
木落 2024-08-14 20:30:34

假设您正在使用 libxml,您可以尝试它的变体(免责声明,这适用于我有限的用例,它可能需要调整才能完全通用)

require 'xml/libxml'

def jasonized
  jsonDoc = xml_to_hash(@doc.root)
  render :json => jsonDoc
end

def xml_to_hash(xml)
  hashed = Hash.new
  nodes = Array.new

  hashed[xml.name+"_attributes"] = xml.attributes.to_h if xml.attributes?
  xml.each_element { |n| 
    h = xml_to_hash(n)
    if h.length > 0 then 
      nodes << h 
    else
      hashed[n.name] = n.content
    end
  }
  hashed[xml.name] = nodes if nodes.length > 0
  return hashed
end

Assuming you're using libxml, you can try a variation of this (disclaimer, this works for my limited use case, it may need tweaking to be fully generic)

require 'xml/libxml'

def jasonized
  jsonDoc = xml_to_hash(@doc.root)
  render :json => jsonDoc
end

def xml_to_hash(xml)
  hashed = Hash.new
  nodes = Array.new

  hashed[xml.name+"_attributes"] = xml.attributes.to_h if xml.attributes?
  xml.each_element { |n| 
    h = xml_to_hash(n)
    if h.length > 0 then 
      nodes << h 
    else
      hashed[n.name] = n.content
    end
  }
  hashed[xml.name] = nodes if nodes.length > 0
  return hashed
end
他是夢罘是命 2024-08-14 20:30:34

简单但依赖重(active_support);如果您已经处于 Rails 环境中,那么这不是什么大问题。

require 'json'
require 'active_support/core_ext'

Hash.from_xml(xml_string).to_json

否则,使用 ox 或 rexml 可能会更好,以获得更轻的依赖性和更高的性能。

Simple but with heavy dependencies (active_support); it's not much of a problem if you already are in a Rails environment.

require 'json'
require 'active_support/core_ext'

Hash.from_xml(xml_string).to_json

Else it would be probably better to use ox or rexml to have much lighter dependencies and more performance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文