brewersfan1976

ch6-ex2.py

Aug 12th, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. # this program takes input from the user and converts it to a JSON string
  2. # then take the JSON string and converts it to XML and writes it to a text file
  3.  
  4. # import the json library
  5.  
  6. import json
  7.  
  8. # open text file to write the XML document to
  9.  
  10. file = open("XML.txt", "w")
  11.  
  12. # create the dictionary to store the data
  13.  
  14. d = {}
  15.  
  16. # get dictionary key from user
  17.  
  18. key = raw_input("Please enter a JSON key or * to quit: ")
  19.  
  20. # if user enters * for a key then quit the program
  21.  
  22. if (key == "*"):
  23.    quit()
  24.  
  25. # get dictionary value from the user
  26.  
  27. value = raw_input("Please enter a JSON value: ")
  28.  
  29. # store the key and value in the dictionary
  30.  
  31. d[key] = value
  32.  
  33. # convert the key and value to XML format and write it to a file
  34.  
  35. string = '<?xml version="1.0"?>\n'
  36. file.write(string)
  37.  
  38. string = "<quotes>\n"
  39. file.write(string)
  40.  
  41. string = "  <stock>\n"
  42. file.write(string)
  43.  
  44. string = "    <company>" + key + "</company>\n"
  45. file.write(string)
  46.  
  47. string = "    <price>" + value + "</price>\n"
  48. file.write(string)
  49.  
  50. string = "  </stock>\n"
  51. file.write(string)
  52.  
  53. # while key is not * repeat the process
  54.  
  55. while(key != "*"):
  56.      key = raw_input("Please enter a JSON key or * to quit: ")
  57.  
  58.      if (key == "*"):
  59.         break
  60.  
  61.      value = raw_input("Please enter a JSON value: ")
  62.      d[key] = value
  63.  
  64.      string = "  <stock>\n"
  65.      file.write(string)
  66.  
  67.      string = "    <company>" + key + "</company>\n"
  68.      file.write(string)
  69.  
  70.      string = "    <price>" + value + "</price>\n"
  71.      file.write(string)
  72.  
  73.      string = "  </stock>\n"
  74.      file.write(string)
  75.  
  76. string = "</quotes>\n"
  77. file.write(string)
  78.  
  79. # convert the dictionary in JSON format and print it out
  80.  
  81. print json.dumps(d)
  82.  
  83. print "The JSON string has been converted to XML and written to a file."
Advertisement
Add Comment
Please, Sign In to add comment