Here when I am converting the XML file to JSON using xmltodict for one value a dict is created while for multiple values a list of dict is created. Below I have attached my python code for XML to JSON conversion and the JSON value: xmltojson.py
with open('books.xml', 'r') as myfile:
obj = xmltodict.parse(myfile.read())
print(json.dumps(obj))
books.xml (for one book value)
<?xml version="1.0"?>
<catalog>
<books>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</books>
</catalog>
Returns the following JSON where book
is of type dict
{
"catalog": {
"books": {
"book": {
"@id": "bk101",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML."
}
}
}
}
While for a books.xml
file having multiple book
<?xml version="1.0"?>
<catalog>
<books>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</books>
</catalog>
The above books.xml
returns a book of type list
{
"catalog": {
"books": {
"book": [
{
"@id": "bk101",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML."
},
{
"@id": "bk101",
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML."
}
]
}
}
}
Even for one value I require List of dict over just a dict.