-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjson_to_xml_ex.rb
50 lines (40 loc) · 1.53 KB
/
json_to_xml_ex.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require 'rubygems'
require 'active_support/core_ext/array/conversions'
require 'json'
require 'cobravsmongoose'
@ecosystems = JSON.parse( File.open( "data/default_ecosystems.json" , "r" ).read )
@name_indexed_ecosystems = JSON.parse( File.open( "data/name_indexed_ecosystems.json" , "r" ).read )
#<ecosystem_0_data>
#</ecosystem_0_data>
# formating operations
def convert_single_level_hash_to_xml( name, b )
# each ecosystem is labled within an opening <pft> and closing </pft> tag
xml_string = "<pft>"
xml_string << "\n\t<name>#{name}</name>\n"
b.each do |key, value|
# if its not a string make it one
if b[key].class.to_s != "String"
b[key] = b[key].to_s
end
# rework data to badgerfish convention
# http://badgerfish.ning.com/
b[key] = { "$" => b[key] }
hash = { "#{key}" => b[key] }
p hash
# parse into XML string
xml = CobraVsMongoose.hash_to_xml(hash)
xml_string << "\t" << xml << "\n"
end
xml_string << "</pft>\n"
end
## Fires off the XML converting process
## Step through each entry of the name-indexed input hash
## and feed in a key like "cars" and the input hash {"domestic"=>"ford","foreign"=>"bugatti"}
## ex = '{"cars"=>{"domestic"=>"ford","foreign"=>"bugatti"},"motorcycles"=>{"domestic"=>"buell","foreign"=>"suzuki"}}'
@name_indexed_ecosystems.each do |key, value|
puts "key #{key}"
puts "value #{value}"
file_string = ""
file_string << convert_single_level_hash_to_xml( key, value )
File.open("config.xml", 'a') { |file| file.write( file_string ) }
end