source

루비 XML-JSON 변환기?

bestscript 2023. 2. 8. 19:41

루비 XML-JSON 변환기?

XML을 JSON으로 변환하는 라이브러리가 루비에 있나요?

간단한 요령:

우선은gem install json레일 사용 시 다음을 수행할 수 있습니다.

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

모든 속성을 유지하고 싶다면 badgerfish 규약을 사용하는 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

당신은 그 보석이 유용하다는 것을 알게 될 것이다.속성, 처리 명령 및 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
    }
  ]
}

의 단순 파생어입니다.

속도를 원하신다면 Ox를 추천합니다. 이미 언급한 옵션 중 가장 빠른 옵션이기 때문입니다.

omg.org/spec의 1.1MB XML 파일을 사용하여 몇 가지 벤치마크를 실행했는데, 결과는 다음과 같습니다(초 단위).

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

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

심플하지만 의존도가 높다(active_support); 이미 Rails 환경을 사용하고 있다면 큰 문제가 되지 않습니다.

require 'json'
require 'active_support/core_ext'

Hash.from_xml(xml_string).to_json

그렇지 않은 경우, 이 제품을 사용하는 것이 더 나을 수 있습니다.ox또는rexml의존성이 훨씬 가벼워지고 퍼포먼스가 향상됩니다.

언급URL : https://stackoverflow.com/questions/1530324/ruby-xml-to-json-converter