Skip to content

Instantly share code, notes, and snippets.

Embed
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):
self._is_json_report_file=False
self._is_xml_report_file=False
self._parsed_report_file=None
if report_input_file is not None:
self.parse_report_file(report_input_file)
@property
def is_json_report_file(self):
return self._is_json_report_file
@property
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
"""
try:
self._parsed_report_file = self._parse_xml_file(report_input_file)
self._is_xml_report_file = True
except ET.ParseError:
try:
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
pass
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(
file_type=file_type,
is_json_report_file=test_class.is_json_report_file,
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.