Ruby XML到JSON转换器?

Lan*_*ard 54 ruby xml json converter

是否有一个库可以在Ruby中将XML转换为JSON?

khe*_*lll 97

一个简单的技巧:

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

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

如果你不使用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
Run Code Online (Sandbox Code Playgroud)

  • 更新,以防您运行ruby脚本与独立程序相同,以避免未定义的方法"from_xml".您需要包含require'active_support/core_ext',如下所示: - http://masonoise.wordpress.com/2010/01/07/hash-from_xml/#comments.这在Rails中工作正常,否则.. (12认同)
  • 有时保持XML属性也很重要.例如,在上面的示例中,"product_code"丢失了.您建议保留属性的库或库是什么? (8认同)
  • 有很好的印刷JSON的小改进:`JSON.pretty_generate(Hash.from_xml('<variable type ="product_code"> 5 </ variable>')) (3认同)
  • 注意你需要`require'json'`和`require'active_support/core_ext'`来让Tom De Leu的例子工作 (3认同)
  • 请注意,您需要需要“json”和“active_support/core_ext/hash” - 而不是“active_support/core_ext” (2认同)

nei*_*fws 24

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

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

myXML  = Crack::XML.parse(File.read("my.xml"))
myJSON = myXML.to_json
Run Code Online (Sandbox Code Playgroud)


Cor*_*ook 13

如果您希望保留所有属性,我建议 使用badgerfish约定的cobravsmongoose http://cobravsmongoose.rubyforge.org/.

<alice sid="4"><bob sid="1">charlie</bob><bob sid="2">david</bob></alice>
Run Code Online (Sandbox Code Playgroud)

变为:

{"alice":{"@sid":"4","bob":[{"$":"charlie","@sid":"1"},{"$":"david","@sid":"2"}]}}
Run Code Online (Sandbox Code Playgroud)

码:

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
Run Code Online (Sandbox Code Playgroud)


Maa*_*ten 5

您可能会发现该xml-to-json宝石很有用。它维护属性,处理指令和DTD语句。

安装

gem install 'xml-to-json'
Run Code Online (Sandbox Code Playgroud)

用法

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
Run Code Online (Sandbox Code Playgroud)

产生:

{
  "type": "element",
  "name": "root",
  "attributes": [
    {
      "type": "attribute",
      "name": "some-attr",
      "content": "hello",
      "line": 1
    }
  ],
  "line": 1,
  "children": [
    {
      "type": "text",
      "content": "ayy lmao",
      "line": 1
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是的简单派生xml-to-hash