Package tlib :: Package base :: Module JsonHelper
[hide private]
[frames] | no frames]

Source Code for Module tlib.base.JsonHelper

  1  import os 
  2  import json 
  3  import jsonpath 
  4  from Helper import Helper 
  5  from HelperException import FileNotExistException, BadFormatException, NotImplementedException 
  6   
  7   
8 -class JsonHelper(Helper):
9 """ 10 Helper class to manipulate the data in Json format 11 """ 12 _obj = None 13 _schema = None 14
15 - def __init__(self, data, schema=None):
16 """ 17 Constructor for class 18 19 @param data : the json string to be processed (alternatively, it can the location of the json file) 20 @param schema : path to the json schema file 21 22 """ 23 Helper.__init__(self) 24 25 ss = data 26 if not data.lstrip().startswith('{'): 27 if os.access(data, os.F_OK): 28 raise FileNotExistException("Json file path location [%s] does not exist or not accessible " % data[:63]) 29 with open(data, 'rb') as fd: 30 ss = fd.read() 31 if not ss.lstrip().startswith('{'): 32 raise BadFormatException('Data provided is not a valid json string:\n%s' % ss[:63]) 33 self._schema = schema 34 try: 35 self._obj = json.loads(data) 36 except Exception as o: 37 raise BadFormatException("Json cannot be parsed with error message:\n%s" % o.error_log.last_error)
38 39
40 - def validateBySchema(self, schema=None):
41 """ 42 Check if Json string is compliant with schema 43 44 Returns : (bool) whether schema validation is passed 45 """ 46 if schema: 47 self._schema = schema 48 if not os.access(self._schema, os.F_OK): 49 raise FileNotExistException("Json schema path location [%s] does not exist or not accessible " % self._schema) 50 with open(self._schema, 'rb') as fd: 51 ss = fd.read() 52 if not ss.lstrip().startswith('{'): 53 raise BadFormatException('Schema file content is not a valid json string\n%s' % ss) 54 raise NotImplementedException('Not fully Implemented')
55 56
57 - def getValuesByJSONPath(self, jpath):
58 """ 59 Get all values using JSONPath 60 61 Args: 62 jpath : JSON-path used to search for values 63 64 For more details about the JSON-Path, please refer to http://goessner.net/articles/JsonPath/ 65 66 Returns : all matching values from JSONPath search in a list 67 """ 68 values = jsonpath.jsonpath(self._obj, jpath) 69 return values if values else []
70 71
72 - def getValueByJSONPath(self, jpath):
73 """ 74 Get the first value using JSONPath 75 76 Args: 77 jpath : JSON-path used to search for values 78 79 For more details about the JSON-Path, please refer to http://goessner.net/articles/JsonPath/ 80 81 Returns : the first matching value from JSONPath search result 82 """ 83 values = self.getValuesByJSONPath(jpath) 84 return values.split(';')[0] if values else None
85 86
87 - def normalizeJSONPath(self, jpath):
88 """ 89 Get the normalized JSONPath 90 91 Args: 92 jpath : JSON-path used to fetch normalized path 93 94 For more details about the JSON-Path, please refer to http://goessner.net/articles/JsonPath/ 95 96 Returns : normalized JSONPath 97 """ 98 paths = jsonpath.jsonpath(self._obj, jpath, result_type="PATH") 99 return paths.split(';')[0] if values else None
100 101 102
103 - def toString(self, pretty_print=True):
104 """ 105 Print Json data in a nice format 106 107 Args: 108 pretty_print : do you want to be pretty? 109 110 Returns : formatted Json string 111 """ 112 separators = None 113 if pretty_print: 114 separators = (',', ': ') 115 return json.dumps(self._obj, separators=separators)
116