Skip to content

Commit c89909e

Browse files
committed
Add SparkData base-class
Add SparkData class to act as a base-class in representing Spark JSON objects as native Python objects.
1 parent 90c6e38 commit c89909e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

ciscosparkapi/sparkdata.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
 (0)