Objective is to convert JSON to XML
The code reads the JSON.txt, converts it into XML and writes it on to JSON_to_xml.txt. The below code returns a value error while unparsing giving an error that the file has multiple roots
even though it has a single root.
import xmltodict
import json
import sys
sys.stdout = open('JSON_to_XML.txt', 'w')
print(json.dumps(xmltodict.unparse(open("JSON.txt", "r").read())))
sys.stdout.close()
The content of the JSON.txt is as follows,
{"note": {"to": "Tove", "from": "Jani", "heading": "Reminder", "body": "Dont forget me this weekend!"}}
If I just copy the contents of the file to the script as shown below, it gives the output in proper XML format.
import xmltodict
import json
print(json.dumps(xmltodict.unparse(
{"note": {"to": "Tove", "from": "Jani", "heading": "Reminder", "body": "Dont forget me this weekend!"}})))
Your comments and suggestions are highly appreciated. Thank you.
Here a dictionary is being passed into the function which is the correct way.
print(json.dumps(xmltodict.unparse({"note": {"to": "Tove", "from": "Jani", "heading": "Reminder", "body": "Dont forget me this weekend!"}})))
But in here the result of read() is a JSON string and is being passed into the function. So, before passing it should be converted into to dictionary.
So the solution would be,
Thank you, Mike: https://github.com/mpf82 for the help.