Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # this program takes input from the user and converts it to a JSON string
- # then take the JSON string and converts it to XML and writes it to a text file
- # import the json library
- import json
- # open text file to write the XML document to
- file = open("XML.txt", "w")
- # create the dictionary to store the data
- d = {}
- # get dictionary key from user
- key = raw_input("Please enter a JSON key or * to quit: ")
- # if user enters * for a key then quit the program
- if (key == "*"):
- quit()
- # get dictionary value from the user
- value = raw_input("Please enter a JSON value: ")
- # store the key and value in the dictionary
- d[key] = value
- # convert the key and value to XML format and write it to a file
- string = '<?xml version="1.0"?>\n'
- file.write(string)
- string = "<quotes>\n"
- file.write(string)
- string = " <stock>\n"
- file.write(string)
- string = " <company>" + key + "</company>\n"
- file.write(string)
- string = " <price>" + value + "</price>\n"
- file.write(string)
- string = " </stock>\n"
- file.write(string)
- # while key is not * repeat the process
- while(key != "*"):
- key = raw_input("Please enter a JSON key or * to quit: ")
- if (key == "*"):
- break
- value = raw_input("Please enter a JSON value: ")
- d[key] = value
- string = " <stock>\n"
- file.write(string)
- string = " <company>" + key + "</company>\n"
- file.write(string)
- string = " <price>" + value + "</price>\n"
- file.write(string)
- string = " </stock>\n"
- file.write(string)
- string = "</quotes>\n"
- file.write(string)
- # convert the dictionary in JSON format and print it out
- print json.dumps(d)
- print "The JSON string has been converted to XML and written to a file."
Advertisement
Add Comment
Please, Sign In to add comment