Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Created January 9, 2010 09:01
Show Gist options
  • Save choonkeat/272815 to your computer and use it in GitHub Desktop.
Save choonkeat/272815 to your computer and use it in GitHub Desktop.
Display xml/json as pretty json
#!/usr/bin/env ruby
#
# Display xml/json as pretty json
#
require 'rubygems'
data = ARGV.first ? IO.read(ARGV.shift) : STDIN.read
while data
begin
require 'json'
x = JSON.load(data)
puts JSON.pretty_generate(x)
rescue JSON::ParserError
require 'hpricot'
x = Hpricot(data)
def xml2hash(root)
if root.respond_to?(:children) && root.children && (children = root.children.reject {|x| x.name.to_s.strip == ''})[1]
name_clash = children.collect {|x| x.name }.uniq! # Returns nil if no changes are made
value = children.inject(name_clash ? [] : {}) do |sum, child|
name_clash ? sum + [xml2hash(child)] : sum.merge(xml2hash(child))
end
root.name.to_s.strip == "" ? value : { root.name => value }
elsif root.name.to_s.strip == ''
root.inner_text.strip
else
{ root.name.to_s.strip => root.inner_text.strip }
end
end
puts JSON.pretty_generate(xml2hash(x))
end
data = ARGV.first ? IO.read(ARGV.shift) : nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment