0

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)
2
  • Dictionary keys cannot be edited, so add new keys and assign them values from old keys (pop) and remove old keys. - Similar question answered: stackoverflow.com/questions/49777924/… Commented Mar 23, 2022 at 20:37
  • @Pankaj Thank you for linking the other answer, I'll have a look. I was thinking maybe there is some way to map xpath for XML file to a list of keys that should be used in JSON. Commented Mar 23, 2022 at 20:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.