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": "[email protected]",
  "@name": "Sam",
}

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

2
  • Can you show the contents of xml file ? Commented Dec 19, 2019 at 6:45
  • @Solen'ya: Below is the xml content. <?xml version="1.0" encoding="UTF-8" standalone="no"?> <PIR:Data xmlns:PIR="google.com"> <CustomerInfo address="Bangalore, Karnataka 560034" email="[email protected]" name="Sam"/> </PIR:Data> Commented Dec 19, 2019 at 7:03

2 Answers 2

6

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='')
Sign up to request clarification or add additional context in comments.

Comments

-1

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": "[email protected]","@name": "Sam"},"Location":{"@Loc":"Mum"}}
removeAtTheRate(doc,{})

Result:

>> {'Location': {'Loc': 'Mum'}, 'CustomerInfo': {'name': 'Sam', 'address': 
'Bangalore, Karnataka 560034', 'email': '[email protected]'}}

2 Comments

The solution by @steve.dev will give wrong output. It will delete the "C" from CustomerInfo key
@ Vaibhav Jadhav: Unfortunately your solution didn't work for my complex json.

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.