Skip to content

Commit f255a9c

Browse files
committed
add json and collections
1 parent f277136 commit f255a9c

17 files changed

Lines changed: 339 additions & 0 deletions
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
"""Iterating over an OrderedDict
5+
"""
6+
7+
import collections
8+
9+
print 'dict :',
10+
d1 = {}
11+
d1['a'] = 'A'
12+
d1['b'] = 'B'
13+
d1['c'] = 'C'
14+
d1['d'] = 'D'
15+
d1['e'] = 'E'
16+
17+
d2 = {}
18+
d2['e'] = 'E'
19+
d2['d'] = 'D'
20+
d2['c'] = 'C'
21+
d2['b'] = 'B'
22+
d2['a'] = 'A'
23+
24+
print d1 == d2
25+
26+
print 'OrderedDict:',
27+
28+
d1 = collections.OrderedDict()
29+
d1['a'] = 'A'
30+
d1['b'] = 'B'
31+
d1['c'] = 'C'
32+
d1['d'] = 'D'
33+
d1['e'] = 'E'
34+
35+
d2 = collections.OrderedDict()
36+
d2['e'] = 'E'
37+
d2['d'] = 'D'
38+
d2['c'] = 'C'
39+
d2['b'] = 'B'
40+
d2['a'] = 'A'
41+
42+
print d1 == d2
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
"""Iterating over an OrderedDict
5+
"""
6+
7+
import collections
8+
9+
print 'Regular dictionary:'
10+
d = {}
11+
d['a'] = 'A'
12+
d['b'] = 'B'
13+
d['c'] = 'C'
14+
d['d'] = 'D'
15+
d['e'] = 'E'
16+
17+
print type(d)
18+
for k, v in d.items():
19+
print k, v
20+
21+
print '\nOrderedDict:'
22+
d = collections.OrderedDict()
23+
d['a'] = 'A'
24+
d['b'] = 'B'
25+
d['c'] = 'C'
26+
d['e'] = 'E'
27+
d['d'] = 'D'
28+
29+
print type(d)
30+
for k, v in d.items():
31+
print k, v

json/json_compact_encoding.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
import json
5+
6+
data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}]
7+
print 'DATA:', repr(data)
8+
print 'repr(data) :', len(repr(data))
9+
print 'dumps(data) :', len(json.dumps(data))
10+
print 'dumps(data, indent=2) :', len(json.dumps(data, indent=2))
11+
print 'dumps(data, separators):', len(json.dumps(data, separators=(',', ':')))
12+
print 'dumps(data, separators):', json.dumps(data, separators=(',', ':'))

json/json_decoder_object_hook.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
import json
5+
6+
7+
class MyDecoder(json.JSONDecoder):
8+
def __init__(self):
9+
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)
10+
11+
def dict_to_object(self, d):
12+
if '__class__' in d:
13+
class_name = d.pop('__class__')
14+
module_name = d.pop('__module__')
15+
module = __import__(module_name)
16+
print 'MODULE:', module
17+
class_ = getattr(module, class_name)
18+
print 'CLASS:', class_
19+
args = dict((key.encode('ascii'), value) for key, value in d.items())
20+
print 'INSTANCE ARGS:', args
21+
inst = class_(**args)
22+
else:
23+
inst = d
24+
return inst
25+
26+
27+
encoded_object = '[{"s": "instance value goes here", "__module__": "json_myobj", "__class__": "MyObj"}]'
28+
29+
myobj_instance = MyDecoder().decode(encoded_object)
30+
print myobj_instance

json/json_dump_default.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
import json
5+
import json_myobj
6+
7+
obj = json_myobj.MyObj('instance value goes here')
8+
9+
print 'First attempt'
10+
try:
11+
print json.dumps(obj)
12+
except TypeError, err:
13+
print 'ERROR:', err
14+
15+
16+
def convert_to_builtin_type(obj):
17+
print 'default(', repr(obj), ')'
18+
# Convert objects to a dictionary of their representation
19+
d = {'__class__': obj.__class__.__name__,
20+
'__module__': obj.__module__,
21+
}
22+
d.update(obj.__dict__)
23+
return d
24+
25+
26+
print
27+
print 'With default'
28+
print json.dumps(obj, default=convert_to_builtin_type)

json/json_dump_file.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
5+
import json
6+
import tempfile
7+
8+
data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}]
9+
10+
f = tempfile.NamedTemporaryFile(mode='w+')
11+
json.dump(data, f)
12+
f.flush()
13+
14+
print open(f.name, 'r').read()

json/json_encoder_default.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
import json
5+
import json_myobj
6+
7+
8+
class MyEncoder(json.JSONEncoder):
9+
def default(self, obj):
10+
print 'default(', repr(obj), ')'
11+
# Convert objects to a dictionary of their representation
12+
d = {'__class__': obj.__class__.__name__,
13+
'__module__': obj.__module__,
14+
}
15+
d.update(obj.__dict__)
16+
return d
17+
18+
19+
obj = json_myobj.MyObj('internal data')
20+
print obj
21+
print MyEncoder().encode(obj)

json/json_encoder_iterable.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
import json
5+
6+
encoder = json.JSONEncoder()
7+
data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}]
8+
9+
for part in encoder.iterencode(data):
10+
print 'PART:', part

json/json_indent.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
import json
5+
6+
data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}]
7+
print 'DATA:', repr(data)
8+
9+
print 'NORMAL:', json.dumps(data, sort_keys=True)
10+
print 'INDENT:', json.dumps(data, sort_keys=True, indent=2)

json/json_load_file.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
import json
5+
import tempfile
6+
7+
f = tempfile.NamedTemporaryFile(mode='w+')
8+
f.write('[{"a": "A", "c": 3.0, "b": [2, 4]}]')
9+
f.flush()
10+
f.seek(0)
11+
12+
print json.load(f)

0 commit comments

Comments
 (0)