I have an XML file like this:
<XML>
<Report>
<ReportNumber>178414417</ReportNumber>
<ReportDatetime>2022-03-23T21:10:04</ReportDatetime>
<Sender>Alexandra Bell</Sender>
<Receiver>Tamara Watson</Receiver>
<MessageToReceiver>Miss Watson, come here, I want to see you.</MessageToReceiver>
</Report>
</XML>
and I would like to transform it into a JSON file which looks like this:
{
"report": {
"report_number": 178414417,
"report_datetime": "2022-03-23T21:10:04",
"sender": "Alexandra Bell",
"receiver": "Tamara Watson",
"message_to_receiver": "Miss Watson, come here, I want to see you"
}
}
I am able to carry out JSON to XML transformation using json
and xmlschema
(simple outline below) but what I'm not sure how to properly add that underscore to keys in JSON (e.g. XML file has element named MessageToReceiver
and its corresponding key in JSON file should be named message_to_receiver
).
import xmlschema
import json
xsd_file = 'xsd_filename.xsd'
xml_file = 'xml_filename.xml'
xml_schema = xmlschema.XMLSchema(xsd_file)
xml_dict = xml_schema.to_dict(xml_file)
json_filename = 'json_filename.json' # Name for JSON file that will be created
with open(json_filename, 'w') as outfile:
json.dump(xml_dict, outfile)
source https://stackoverflow.com/questions/71593577/python-how-to-transform-json-file-into-an-xml-file-and-modify-its-keys
Comments
Post a Comment