Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How to traverse nested JSON object and delete/modify them using Python after parsing the XML file?

$
0
0

Given XML, I need to convert it to JSON and modify the JSON object.

<?xml version="1.0" standalone="yes"?><!--COUNTRIES is the root element--><WORLD><country name="A"><event day="323" name="$abcd"> </event><event day="23" name="$aklm"> </event><neighbor name="B" direction="W" friend="T"/neighbor><neighbor name="B" direction="W"/neighbor><neighbor name="B" direction="W"/neighbor></country><country name="C"><event day="825" name="$nmre"> </event><event day="329" name="$lpok"> </event><event day="145" name="$dswq"> </event><event day="256" name="$tyul"> </event><neighbor name="D" direction="N"/><neighbor name="B" direction="W" friend="T"/></country></WORLD>

I want to remove "event" element in the final output of JSON file, and "friend" attribute, which is present inside "WORLD"-> "country"-> "neighbor".I am using "xmltodict" library in Python and successfully able to convert XML to JSON, but could not able to remove these elements and attributes from JSON file.

Python Code:

import Xmltodict, JSONclass XMLParser:    def __init__(self, xml_file_path):        self.xml_file_path = xml_file_path        if not self.xml_file_path:            raise ValueError("XML file path is not found./n")        with open (self.xml_file_path, 'r') as f:            self.xml_file = f.read()    def parse_xml_to_json(self):        xml_file = self.xml_file        json_data = xmltodict.parse(xml_file, attr_prefix='')        if 'event' in json_data['WORLD']['country']:            del json_data['WORLD']['country']['event']        return json.dumps(json_data, indent=4)xml_file_path = "file_path"xml_parser = XMLParser(xml_file_path)json_object = xml_parser.parse_xml_to_json()print(json_object)

Please suggest.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>