1

I have a folder with 1000's of XML files. Now I would like to read each xml file and create a json file for that respective xml file without deleting the xml file.

For example: if I have a file named abc.xml I want that xml file to be converted into json and stored as abc.json so the folder should have abc.xml, abc.json and it should be the same for all the files.

Currently, I am using the below code chunk to convert the xml to json but the issue is it is not creating a new json file.

for filename in os.listdir(path):
    if not filename.endswith('.xml'): continue
    fullname = os.path.join(path, filename)
    with open(fullname, 'r') as f:
        xmlString = f.read()
    jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)
    with open(fullname, 'w') as x:
        x.write(jsonString)

Any kind of relevant suggestions would be really appreciated.

2
  • looks that you're overwriting your xml file, you're not changing the file name Commented Oct 25, 2018 at 19:32
  • Yes, that's exactly what's happening which I don't want. I want to create a new json file for that xml file. Commented Oct 25, 2018 at 19:34

2 Answers 2

2

fullname is the name of your input xml file. You want to change it to "same thing but json" else you'll create a file with xml extension but json data (destroying your original xml file, not that I care about xml much but...)

with open(fullname, 'r') as f:
    xmlString = f.read()
json_output = os.path.splitext(fullname)[0]+".json"

now write your file directly (no need to create a string first)

with open(json_output, 'w') as f:
    json.dump(xmltodict.parse(xmlString), f, indent=4)

note that you could use glob.glob directly like this so you get the full, xml filtered path:

for fullname in glob.glob(os.path.join(path,"*.xml"):
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jean. Working perfectly. Appreciate your help.
0

This should work.

import xmltodict

for filename in os.listdir(path):
    if not filename.endswith('.xml'):
        continue

    fullname = os.path.join(path, filename)

    with open(fullname, 'r') as f:
        xmlString = f.read()

    jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)

    with open(fullname[:-4] + ".json", 'w') as f:
        f.write(jsonString)

Comments

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.