1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import json
d = dict(name='Tom', age=20, score=80) json_str = json.dumps(d) print(json_str)
json_str = '{"age": 20, "score": 80, "name": "Tom"}' d = json.loads(json_str) print(d)
class Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score
def student2dict(std): return { 'name': std.name, 'age': std.age, 'score': std.score }
def dict2student(d): return Student(d['name'], d['age'], d['score'])
s = Student('Tom', 20, 80) json_str = json.dumps(s, default=student2dict) print(json_str)
json_str = '{"age": 20, "score": 80, "name": "Tom"}' s = json.loads(json_str, object_hook=dict2student) print(s.name, s.age, s.score)
with open("../config/record.json",'r') as load_f: load_dict = json.load(load_f)
with open("../config/record.json","w") as dump_f: json.dump(load_dict,dump_f)
with open("../config/record.json", "w", encoding='utf-8') as dump_f: json.dump(result, dump_f, ensure_ascii=False)
|