Skip to main content

Serialization for JSON and XML using typing

Project description

jetblack-serialization

Serialization for JSON and XML in Python using typing

Status

Work in progress

Overview

Given a typed dictionary:

from datetime import datetime
from typing import List, Optional, TypedDict, Union

class Book(TypedDict, total=False):
    book_id: int
    title: str
    author: str
    publication_date: datetime
    keywords: List[str]
    phrases: List[str]
    age: Optional[Union[datetime, int]]
    pages: Optional[int]

JSON

This could be serialized to JSON as:

from stringcase import camelcase, snakecase
from jetblack_serialize import SerializerConfig
from jetblack_serialize.json import serialize

obj: Book = {
    'author': 'Chairman Mao',
    'book_id': 42,
    'title': 'Little Red Book',
    'publication_date': datetime(1973, 1, 1, 21, 52, 13),
    'keywords': ['Revolution', 'Communism'],
    'phrases': [
        'Revolutionary wars are inevitable in class society',
        'War is the continuation of politics'
    ],
    'age': 24,
}
text = serialize(
    obj,
    Book,
    SerializerConfig(camelcase, snakecase, pretty_print=True)
)
print(text)

giving:

{
    "bookId": 42,
    "title": "Little Red Book",
    "author": "Chairman Mao",
    "publicationDate": "1973-01-01T21:52:13.00Z",
    "keywords": ["Revolution", "Communism"],
    "phrases": ["Revolutionary wars are inevitable in class society", "War is the continuation of politics"],
    "age": 24,
    "pages": null
}

Note the fields have been camel cased, and the publication date has been turned into an ISO 8601 date.

XML

The XML version of the typed dictionary might look like this:

from datetime import datetime
from typing import List, Optional, TypedDict, Union
from typing_extensions import Annotated
from jetblack_serialization import XMLEntity, XMLAttribute

class Book(TypedDict, total=False):
    book_id: Annotated[int, XMLAttribute("bookId")]
    title: str
    author: str
    publication_date: datetime
    keywords: Annotated[List[Annotated[str, XMLEntity("Keyword")]], XMLEntity("Keywords")]
    phrases: List[str]
    age: Optional[Union[datetime, int]]
    pages: Optional[int]

To serialize we need to provide the containing tag Book:

from stringcase import pascalcase, snakecase
from jetblack_serialize import SerializerConfig
from jetblack_serialize.xml import serialize

book: Book = {
    'author': 'Chairman Mao',
    'book_id': 42,
    'title': 'Little Red Book',
    'publication_date': datetime(1973, 1, 1, 21, 52, 13),
    'keywords': ['Revolution', 'Communism'],
    'phrases': [
        'Revolutionary wars are inevitable in class society',
        'War is the continuation of politics'
    ],
    'age': 24,
    'pages': None
}
text = serialize(
    book,
    Annotated[Book, XMLEntity("Book")],
    SerializerConfig(pascalcase, snakecase)
)
print(text)

Producing:

<Book bookId="42">
    <Title>Little Red Book</Title>
    <Author>Chairman Mao</Author>
    <PublicationDate>1973-01-01T21:52:13.00Z</PublicationDate>
    <Keywords>
        <Keyword>Revolution</Keyword>
        <Keyword>Communism</Keyword>
    </Keywords>
    <Phrase>Revolutionary wars are inevitable in class society</Phrase>
    <Phrase>War is the continuation of politics</Phrase>
    <Age>24</Age>
</Book>'

The annotations are more elaborate here. However, much of the typed dictionary requires no annotation.

First we needed the outer document wrapper XMLEntity("Book").

Next we annotated the book_id to be an XMLAttribute.

Finally we annotated the two lists differently. The keywords list used a nested structure, which we indicated by giving th list a different XMLEntity tag to the list items. For the phrases we used the default in-line behaviour.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jetblack-serialization-0.1.0.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jetblack_serialization-0.1.0-py3-none-any.whl (24.0 kB view details)

Uploaded Python 3

File details

Details for the file jetblack-serialization-0.1.0.tar.gz.

File metadata

  • Download URL: jetblack-serialization-0.1.0.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.0.2 CPython/3.7.5 Linux/5.3.0-26-generic

File hashes

Hashes for jetblack-serialization-0.1.0.tar.gz
Algorithm Hash digest
SHA256 e97d2e8413fc63b87e983a40b6c3b640ca8bd09ab7fb41aba648da81d9ceb66e
MD5 032c3e9091ebeed1713216b9671f5eb6
BLAKE2b-256 1e970ff84af7e689596c27bb72de56a0c20827a78b4ab441bd3a1f455d9e54fb

See more details on using hashes here.

File details

Details for the file jetblack_serialization-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for jetblack_serialization-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 57b80207f4ab3bc8ca40fffcc837f23b8a421a9a8cb5b6f80a46ad7d25bbe14b
MD5 5df7160ef265da0ea95984522fc4e09f
BLAKE2b-256 7373e6f301bfa94be638c1fc70420e4fa729be8df2e60341baaba66b81dc57d3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page