python: json Deserialization of Python dict

 

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
54
55
56
from typing import List
import json
 
 
class Student(object):
    def __init__(self, first_name: str, last_name: str):
        self.first_name = first_name
        self.last_name = last_name
 
    @property
    def FirstNmae(self):
        return  self.first_name
 
    @property
    def LastNmae(self):
        return  self.last_name
 
 
 
class Team(object):
    def __init__(self, students: List[Student]):
        self.students = students
 
 
def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name} world,geovindu,涂聚文'# Press Ctrl+F8 to toggle the breakpoint.
 
 
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm,geovindu')
 
    student1 = Student(first_name="Geeky", last_name="Guy")
    student2 = Student(first_name="GFG", last_name="Rocks")
    team = Team(students=[student1, student2])
 
    # Serialization
    json_data = json.dumps(team, default=lambda o: o.__dict__, indent=4)
    print(json_data)
 
    # Deserialization
    decoded_team = Team(**json.loads(json_data))
    print(type(decoded_team.students))
    for Student in decoded_team.students:
        sd=Student
        print(sd["first_name"],sd["last_name"])
 
    teamobje = json.loads(json_data)
    with open("weatherdatafile.json", "w", encoding='utf-8') as write:
        json.dump(teamobje, write, indent=4# 可以写成文件
 
    with open('weatherdatafile.json',encoding='utf-8') as json_file:
        data = json.load(json_file)
        print("data from file:")
        print(data)

  

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
import json
import pickle
from marshmallow import Schema, fields, validate
 
from dataclasses import dataclass
from typing import Optional, List
 
@dataclass
class Book:
    title: str
    isbn: str
 
@dataclass
class User:
    email: str
    books: Optional[List[Book]] = None
 
def validate_isbn(isbn: str) -> None:
    """ Validates the isbn with some code (omitted), raise marshmallow.ValidationError if validation did not pass """
 
class BookSchema(Schema):
    title = fields.String(required=True, validate=validate.Length(max=120))
    isbn = fields.String(required=True, validate=validate_isbn)
 
class UserSchema(Schema):
    email = fields.Email(required=True)
    books = fields.Nested(BookSchema, many=True, required=False)
 
 
def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name} world,geovindu,涂聚文'# Press Ctrl+F8 to toggle the breakpoint.
 
 
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm,geovindu')
     
    #deserialization process:
    raw_data_str = """{
        "email": "foo@bar.com",
        "books": [
            {"title": "Hitchhikers Guide to the Galaxy", "isbn": "123456789"},
            {"title": "Clean Coder", "isbn": "987654321"}
        ]
    }"""
    json_data = json.loads(raw_data_str)
 
    schema = UserSchema()
    user = schema.load(json_data)  # raises if validation fails
    print(type(user))  # 辞典类型 dict
    print(user)

  

https://www.augmentedmind.de/2020/10/25/marshmallow-vs-pydantic-python/
https://www.kimsereylam.com/python/2019/10/25/serialization-with-marshmallow.html
https://github.com/marshmallow-code/marshmallow
https://marshmallow.readthedocs.io/en/stable/

 

posted @   ®Geovin Du Dream Park™  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2021-12-14 java:create package
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示