Skip to content

Instantly share code, notes, and snippets.

@jlindsey
Created March 24, 2010 19:58
Show Gist options
  • Save jlindsey/342711 to your computer and use it in GitHub Desktop.
Save jlindsey/342711 to your computer and use it in GitHub Desktop.
A super simple XML to JSON file converter
#! /usr/bin/env ruby
require 'rubygems'
require 'active_support'
require 'json'
require 'commander/import'
program :name, "xml2json"
program :version, "1.1.0"
program :description, "XML to JSON converter"
default_command :'convert file'
command :'convert file' do |c|
c.syntax = 'convert file <input> <output>'
c.description = 'converts specified input XML file into a JSON file at the specified location'
c.when_called do |args, options|
if args.length != 2
puts "Wrong number of arguments. See usage (xml2json -h convert file)"
exit(1)
end
json_str = Hash.from_xml(File.open(args.first).read).to_json
File.open(args.last, 'w+').write json_str
end
end
command :in do |c|
c.syntax = 'in'
c.description = 'takes an XML string from stdin and puts the converted JSON into stdout'
c.when_called { |args, options| puts Hash.from_xml($stdin.gets).to_json }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment