How can I keep the position of keys when I rename the name of key in ruby hash?



I want to covert json to xml. At first, I converted json to hash because I want to change the name of some keys. I used mappings for the change.



@issue_xml = "tmp.xml"

issues = File.new(@issue_xml, File::WRONLY|File::TRUNC|File::CREAT)

issues.puts "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"

issues.puts "<errorList xmlns=\"http://ift.tt/1onFIxP\" version=\"9.5.2\">"
mappings = {"id" => "problemID","severityCode" => "severitylevel","status" => "citingStatus"}

my_hash = JSON.parse(line)
my_hash.keys.each { |k| my_hash[ mappings[k] ] = my_hash.delete(k) if mappings[k] }


my_xml = my_hash.to_xml(:root => 'problem')

my_xml.each_line do |line|
next if line.start_with?("<?xml") or line.eql?("<hash>") or line.eql?("</hash>")
issues.puts line
end
issues.puts "</errorList>"

issues.close


With the code above, I can generate a xml file. But the result is a little different from that I expect.


Here is my question.


I hope that key 'problemID' appear in the beginning of the each problem. but newly mapped keys 'problemID, severityCode, citingStatus' are moved to the end.


Could you let me know how I can keep the positions of the keys?


Thanks alot.


No comments:

Post a Comment