Created
March 4, 2016 08:11
-
-
Save ueki-kazuki/973e448f52567b02ade4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rexml/document' | |
require 'json' | |
file = ARGV[0] | |
class REXML::Element | |
def to_h | |
hash = {} | |
if self.has_elements? | |
self.elements.each do |e| | |
if e.has_elements? | |
if hash[e.name].nil? | |
hash[e.name] = e.to_h | |
elsif hash[e.name].is_a?(Array) | |
hash[e.name].push( e.to_h ) | |
else | |
hash[e.name] = [ hash[e.name] ] | |
hash[e.name].push( e.to_h ) | |
end | |
elsif e.has_text? | |
hash[e.name] = e.text | |
end | |
end | |
else | |
hash[self.name] = self.text | |
end | |
hash | |
end | |
end | |
doc = REXML::Document.new open(file).read | |
obj = doc.root.to_h | |
puts JSON.dump(obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment