Home > Mobile >  Python JSON to XML conversion without json2xml library
Python JSON to XML conversion without json2xml library

Time:03-18

I am just getting started with Python and I am trying to convert a JSON file to XML. I have looked at lots of tutorials and messed about with the code but I am stuck. Here is a snippet of the JSON file:

{
    "students":[
    {"id":897654,
        "fullName":{
            "title":"Mrs",
            "first":"Lisa",
            "surname":"Penny",
            "other":["Melanie"]},
        "age": 32,
        "city": "London"},

    {"id":786789,
        "fullName":{
            "title":"Mr",
            "first":"Lorenzo",
            "surname":"Dubois",
            "other":["Ruelle", "Garlen"]},
        "age": 38,
        "city": "Paris"},

And here is the code I am working with:

with open('People.json', 'r') as json_file:
    data = js.load(json_file)

root = et.Element('students')

_id = et.SubElement(root, 'id').text = data['students']['id']

I get the error: list indices must be integers or slices, not str

CodePudding user response:

data['students'] is a list, whose elements are dictionaries with an id key; data['students'] itself has no such key.

  • Related