|
| 1 | +"""SparkData base-class; represents Spark JSON as native Python objects.""" |
| 2 | + |
| 3 | + |
| 4 | +import json as json_pkg |
| 5 | + |
| 6 | + |
| 7 | +def _json_dict(json): |
| 8 | + if isinstance(json, dict): |
| 9 | + return json |
| 10 | + elif isinstance(json, basestring): |
| 11 | + return json_pkg.loads(json) |
| 12 | + else: |
| 13 | + error = "'json' must be a dictionary or string; " \ |
| 14 | + "received: %r" % json |
| 15 | + raise TypeError(error) |
| 16 | + |
| 17 | + |
| 18 | +class SparkData(object): |
| 19 | + """Represents Spark JSON as native Python objects.""" |
| 20 | + |
| 21 | + def __init__(self, json): |
| 22 | + super(SparkData, self).__init__() |
| 23 | + self._json = _json_dict(json) |
| 24 | + |
| 25 | + def __getattr__(self, item): |
| 26 | + if item in self._json.keys(): |
| 27 | + item_data = self._json[item] |
| 28 | + if isinstance(item_data, dict): |
| 29 | + return SparkData(item_data) |
| 30 | + else: |
| 31 | + return item_data |
| 32 | + else: |
| 33 | + error = "'%s' object has no attribute '%s'" % \ |
| 34 | + (self.__class__.__name__, item) |
| 35 | + raise AttributeError(error) |
| 36 | + |
| 37 | + def __str__(self): |
| 38 | + class_str = self.__class__.__name__ |
| 39 | + json_str = json_pkg.dumps(self._json, indent=2) |
| 40 | + return "%s:\n%s" % (class_str, json_str) |
| 41 | + |
| 42 | + def __repr__(self): |
| 43 | + class_str = self.__class__.__name__ |
| 44 | + json_str = json_pkg.dumps(self._json, ensure_ascii=False) |
| 45 | + return "%s(%r)" % (class_str, json_str) |
0 commit comments