1

I'm trying to convert xml to json in python using xmltodict library. Though, the xml is getting converted to json, before every key in dict, '@' is getting prefixed. Below is the code snippet and sample output:

import xmltodict
import json

with open('response.xml','r') as res_file:
    doc = xmltodict.parse(res_file.read())

xml_json_str = json.dumps(doc)
final_json = json.loads(xml_json_str)

Output:

"CustomerInfo": {
  "@address": "Bangalore, Karnataka 560034",
  "@email": "abc@gmail.com",
  "@name": "Sam",
}

How to remove @ from all key's at one go?

Sumit
  • 1,360
  • 3
  • 16
  • 29

2 Answers2

4

Finally I found a solution which works like charm. While parsing the xml, set attr_prefix='' to remove all @ from keys.

Below changes worked for me:

with open('response.xml','r') as res_file:
    doc = xmltodict.parse(res_file.read(), attr_prefix='')
Sumit
  • 1,360
  • 3
  • 16
  • 29
0

Check this out: It will remove all the @ from all keys be it in any node: I have added one extra note just to show you the example:

def removeAtTheRate(jsonFile,final_json_edited):
    if jsonFile != {} and type(jsonFile) == dict:
        for i in jsonFile.keys():
            final_json_values = {}
            for j in jsonFile[i]:
                if j[:1] == '@':
                    final_json_values[j[1:]] = jsonFile[i][j]
            if i[:1] == '@':
                final_json_edited[i[1:]] = final_json_values
            else:
                final_json_edited[i] = final_json_values
    print(final_json_edited)

doc = {"@CustomerInfo":{"@address": "Bangalore, Karnataka 560034","@email": "abc@gmail.com","@name": "Sam"},"Location":{"@Loc":"Mum"}}
removeAtTheRate(doc,{})

Result:

>> {'Location': {'Loc': 'Mum'}, 'CustomerInfo': {'name': 'Sam', 'address': 
'Bangalore, Karnataka 560034', 'email': 'abc@gmail.com'}}
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20