python: json Deserialization of Python dict

 

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)

  

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 @ 2023-12-14 20:29  ®Geovin Du Dream Park™  阅读(11)  评论(0编辑  收藏  举报