Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 38624c3

Browse files
committed
add pickle and json samples
1 parent 32347c1 commit 38624c3

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

py3/io/use_json.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import json
5+
6+
d = dict(name='Bob', age=20, score=88)
7+
data = json.dumps(d)
8+
print('JSON Data is a str:', data)
9+
reborn = json.loads(data)
10+
print(reborn)
11+
12+
class Student(object):
13+
14+
def __init__(self, name, age, score):
15+
self.name = name
16+
self.age = age
17+
self.score = score
18+
19+
def __str__(self):
20+
return 'Student object (%s, %s, %s)' % (self.name, self.age, self.score)
21+
22+
s = Student('Bob', 20, 88)
23+
std_data = json.dumps(s, default=lambda obj: obj.__dict__)
24+
print('Dump Student:', std_data)
25+
rebuild = json.loads(std_data, object_hook=lambda d: Student(d['name'], d['age'], d['score']))
26+
print(rebuild)

py3/io/use_pickle.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import pickle
5+
6+
d = dict(name='Bob', age=20, score=88)
7+
data = pickle.dumps(d)
8+
print(data)
9+
10+
reborn = pickle.loads(data)
11+
print(reborn)

0 commit comments

Comments
 (0)