Skip to content

Instantly share code, notes, and snippets.

@jamesduncombe
Created October 4, 2012 17:51
Show Gist options
  • Save jamesduncombe/3835251 to your computer and use it in GitHub Desktop.
Save jamesduncombe/3835251 to your computer and use it in GitHub Desktop.
Script to convert a series of XML documents into an Array of Hashes then to a JSON file
#
# Read a series of XML documents into a large Array of Hashes
# export as JSON
#
# assign some constants to handle file names / paths
PATH_TO_XML_FILES, EXPORT_FILE = ARGV.first, ARGV.last
# argument validation
raise ArgumentError, 'You must specify a path from which to read the XML documents' if PATH_TO_XML_FILES.nil?
raise ArgumentError, 'You must specify an output file' if EXPORT_FILE.nil?
# an empty array for our Hashes
arr = []
# iterate over each file in the input directory
Dir.foreach(PATH_TO_XML_FILES) do |file|
# check file is XML
if file =~ /.xml/
# open the file and read
File.open(PATH_TO_XML_FILES+'/'+file) do |f|
# read from the file then convert to ruby Hash and append to array
arr << Hash.from_xml(f.read)
end
end
end
# write the contents to a json file
File.open(PATH_TO_XML_FILES+'/'+EXPORT_FILE, 'w+') do |f|
f.write(arr.to_json)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment