developer tip

Ruby XML to JSON 변환기?

optionbox 2021. 1. 10. 17:06
반응형

Ruby XML to JSON 변환기?


Ruby에서 XML을 JSON으로 변환하는 라이브러리가 있습니까?


간단한 트릭 :

먼저 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

간단한 XML 및 JSON 파서 인 Crack을 사용 합니다.

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

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

모든 속성을 유지 하려면 오소리 규칙을 사용하는 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

xml-to-json보석이 유용하다는 것을 알 수 있습니다 . 속성, 처리 명령 및 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.


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

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

ReferenceURL : https://stackoverflow.com/questions/1530324/ruby-xml-to-json-converter

반응형