Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python class with init method to parse json / xml to test valid formats. Example of @Property usage and some EAFP style exception handling.
from __future__ import print_function
import xml.etree.cElementTree as ET
import json
class ReportDocument(object):
ReportDocument is an abstraction of a JSON, XML or neither file type.
def __init__(self, report_input_file=None, *args, **kwargs):
if report_input_file is not None:
def is_json_report_file(self):
return self._is_json_report_file
def is_xml_report_file(self):
return self._is_xml_report_file
def _parse_json_file(self,report_input_file):
Given a text file, returns a JSON object or None
with open(report_input_file,'rb') as in_file:
return json.load(in_file)
def _parse_xml_file(self,report_input_file):
Given a text file, returns an XML element or None
with open(report_input_file,'rb') as in_file:
return ET.parse(in_file)
def parse_report_file(self, report_input_file):
Checks if input report file is of type json or xml
returns a json object or an xml element or None
self._parsed_report_file = self._parse_xml_file(report_input_file)
self._is_xml_report_file = True
except ET.ParseError:
self._parsed_report_file = self._parse_json_file(report_input_file)
self._is_json_report_file = True
except ValueError: # or in Python3 the specific error json.decoder.JSONDecodeError
if __name__ == '__main__':
files_to_test = ['real.xml', 'real.json', 'blank.txt']
for file_type in files_to_test:
test_class = ReportDocument(file_type)
print("{file_type}: \n\t is_json:{is_json_report_file} \n\t is_xml:{is_xml_report_file}".format(
is_xml_report_file = test_class.is_xml_report_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.