cbor2 #6752
cbor2
#6752
Replies: 1 comment
|
InstallJust add it to your dependencies: [project]
dependencies = [
"flet",
"cbor2==6.1.4",
]ExampleEncodes a record JSON can't represent (raw import json
import cbor2
import flet as ft
def main(page: ft.Page):
page.title = "cbor2 demo"
record = {
"id": 7,
"name": "sensor-α",
"reading": 21.5,
"raw": b"\x00\x01\x02\x03", # bytes are native in CBOR — impossible in JSON
"big": 2**100, # >64-bit int → CBOR bignum tag
}
payload = cbor2.dumps(record)
ok = cbor2.loads(payload) == record
# closest JSON equivalent needs hex/str workarounds:
json_size = len(json.dumps({**record, "raw": record["raw"].hex(), "big": str(record["big"])}))
page.add(
ft.Text(f"cbor2 round-trip {'OK ✅' if ok else 'FAILED ❌'}", weight=ft.FontWeight.BOLD),
ft.Text(f"CBOR payload: {len(payload)} bytes (JSON equivalent: {json_size} bytes)"),
ft.Text(f"hex: {payload.hex()[:48]}…", font_family="monospace"),
)
ft.run(main)Things to know
|
0 replies
Answer selected by
ndonkoHenri
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cbor21.6.4 is now supported on Android and iOS: https://pypi.flet.dev/cbor2cbor2gives you CBOR (RFC 8949) — a binary, schema-less serialization format with the same data model as JSON plus nativebytes, big integers, decimals, and tagged types, in a fraction of the size. The API mirrorsjson:cbor2.dumps/cbor2.loads/dump/load.Install
Just add it to your dependencies:
Example
Encodes a record JSON can't represent (raw
bytes, a 100-bit integer), decodes it back, and shows the size win on screen: