xmltodict: unparsing raises ValueError('Document must have exactly one root.') - Python 3

1.4k views Asked by At

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.

1

There are 1 answers

0
Ramsey On

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.

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()

So the solution would be,

import json
import sys

# JSON to XML

f = open("JSON.txt")

sys.stdout = open('JSON_to_XML.txt', 'w')
print(json.dumps(xmltodict.unparse(json.load(f))))
sys.stdout.close()

Thank you, Mike: https://github.com/mpf82 for the help.