- Part 12 of 21 in System Design Roadmap: From Beginner to Intermediate Architecture Beginner
Data Serialization Formats Explained: JSON and XML vs. Binary Schemas (Protobuf, Avro)
Master data serialization, compare text and binary representations, and implement reliable encoding, parsing, and schema validation in Python.
MonksBit Desk
November 25, 2026 · 9 min read · 31 views
Read
Data serialization is the process of translating in-memory data structures or objects into a standardized format that can be stored in a file or transmitted across a network, while deserialization reconstructs the original object state from that serialized format.
You will need. Basic knowledge of Python dictionaries and file operations · Understanding of in-memory data structures like trees and key-value maps
The full lesson
Level 1 · Beginner: Core concepts of text-based serialization using JSON and XML
In modern computing, programs store variables and objects in dynamic computer memory. However, internal memory layouts rely on specific memory addresses, pointers, and CPU architectures. When two distinct processes need to exchange information across a network or save records to disk, they require a universal medium that is independent of hardware and programming language.
The two most widespread historical human-readable formats are JSON (JavaScript Object Notation) and XML (Extensible Markup Language). JSON structures data using key-value mappings and ordered lists, making it lightweight and natively compatible with modern web languages. XML structures data hierarchically using open and closing tags with attributes, providing explicit tree modeling at the cost of textual verbosity.
To illustrate the difference on a concrete record, suppose we wish to represent a user with an identifier of 101, a name Alice, and an active status set to true. In JSON, this is written as a set of curly braces containing string keys mapped to values. In XML, each field is enclosed by matching tags.
The following code demonstrates how to serialize a Python dictionary into both JSON and XML strings, and then parse those strings back into Python objects.
Basic serialization and deserialization with JSON and XML
import jsonimport xml.etree.ElementTree as ETdata = {"id": 101, "name": "Alice", "active": True}# JSON serialization and deserializationjson_text = json.dumps(data)print("JSON Output:", json_text)parsed_json = json.loads(json_text)assert parsed_json["name"] == "Alice"# XML serializationroot = ET.Element("user")for key, value in data.items(): child = ET.SubElement(root, key) child.text = str(value)xml_text = ET.tostring(root, encoding="utf-8").decode("utf-8")print("XML Output:", xml_text)# XML deserializationparsed_root = ET.fromstring(xml_text)parsed_xml = { "id": int(parsed_root.find("id").text), "name": parsed_root.find("name").text, "active": parsed_root.find("active").text == "True",}assert parsed_xml["name"] == "Alice"
Key takeaways
- Serialization converts in-memory objects into portable byte or character sequences.
- JSON maps naturally to standard primitive types like numbers, strings, lists, and maps.
- XML relies on nested hierarchical tags, requiring explicit string parsing to recover native types.
Level 2 · Intermediate: Handling schema validation, type integrity, and parsing boundaries
In production environments, unvalidated deserialization is a severe defect. Text formats like JSON do not natively enforce schemas, nor do they support arbitrary types such as dates, byte arrays, or custom classes without explicit conversion conventions.
Furthermore, naive XML parsers are notoriously vulnerable to external entity injection (XXE) and billion-laughs recursive entity expansion attacks. When parsing XML, parsers must disable document type definitions (DTD) and entity resolution to remain safe.
Handling edge cases requires explicit data validation: handling empty inputs, verifying field presence, checking value bounds, and converting string timestamps into structured objects. When serializing data structures with non-string keys or complex objects, custom encoders and deserializers must be defined.
Below is an example showing safe parsing, custom date serialization in JSON, and defensive error handling against malformed inputs.
Defensive JSON serialization with custom types and validation
import jsonfrom datetime import datetime, timezonefrom typing import Any, Dictclass UserProfile: def __init__(self, user_id: int, username: str, created_at: datetime): if not isinstance(user_id, int) or user_id <= 0: raise ValueError("user_id must be a positive integer") if not username or not isinstance(username, str): raise ValueError("username must be a non-empty string") self.user_id = user_id self.username = username self.created_at = created_atclass ProfileEncoder(json.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, datetime): return obj.isoformat() if isinstance(obj, UserProfile): return { "user_id": obj.user_id, "username": obj.username, "created_at": obj.created_at.isoformat() } return super().default(obj)def parse_user_profile(payload: str) -> UserProfile: if not payload or not payload.strip(): raise ValueError("Input payload is empty") raw_dict: Dict[str, Any] = json.loads(payload) required_fields = {"user_id", "username", "created_at"} if not required_fields.issubset(raw_dict.keys()): missing = required_fields - raw_dict.keys() raise KeyError(f"Missing required fields: {missing}") parsed_time = datetime.fromisoformat(raw_dict["created_at"]) return UserProfile(raw_dict["user_id"], raw_dict["username"], parsed_time)# Example usageuser = UserProfile(42, "dev_monk", datetime.now(timezone.utc))serialized = json.dumps(user, cls=ProfileEncoder)restored = parse_user_profile(serialized)assert restored.user_id == 42assert restored.username == "dev_monk"
Key takeaways
- Custom encoders are required for non-primitive types like datetimes and custom class instances.
- Deserialization must always validate incoming fields and enforce structural schema rules.
- Empty strings, missing keys, and unexpected types must be handled prior to business logic execution.
Level 3 · Advanced: Binary serialization trade-offs, schemas, and high-performance protocols
While JSON and XML excel at human inspectability and web API interoperability, their textual representation introduces high CPU parsing overhead and substantial network bandwidth waste due to repeated field keys and ASCII encoding of numbers.
High-throughput distributed systems rely on binary serialization formats such as Protocol Buffers, Apache Avro, FlatBuffers, and MessagePack. These formats replace repetitive field strings with numeric tag identifiers, compact variable-length integers (varints), and pre-compiled schemas. FlatBuffers goes further by eliminating an explicit unpacking step entirely, allowing values to be accessed directly from serialized memory offsets.
Schema evolution is the principal architectural challenge with binary formats. When a service upgrades its data schema, it must maintain forward compatibility (older services can read data written by newer services) and backward compatibility (newer services can read data written by older services). This is accomplished by assigning permanent, immutable field indices and never reusing removed tag numbers.
The following implementation demonstrates a compact binary serializer simulating schema-driven binary encoding with variable-length integer encoding (varint) and tag-based field identification.
Schema-driven binary serialization with varints and field tags
import iodef encode_varint(value: int) -> bytes: result = bytearray() while value >= 0x80: result.append((value & 0x7F) | 0x80) value >>= 7 result.append(value & 0x7F) return bytes(result)def decode_varint(stream: io.BytesIO) -> int: result = 0 shift = 0 while True: byte_data = stream.read(1) if not byte_data: raise EOFError("Unexpected end of stream") byte = byte_data[0] result |= (byte & 0x7F) << shift if not (byte & 0x80): break shift += 7 return resultdef serialize_record(user_id: int, username: str) -> bytes: buf = bytearray() # Field 1: user_id (varint) buf.extend(encode_varint(1)) buf.extend(encode_varint(user_id)) # Field 2: username (length-prefixed utf-8 string) name_bytes = username.encode("utf-8") buf.extend(encode_varint(2)) buf.extend(encode_varint(len(name_bytes))) buf.extend(name_bytes) return bytes(buf)def deserialize_record(data: bytes) -> dict: stream = io.BytesIO(data) result = {} while True: tag_byte = stream.read(1) if not tag_byte: break stream.seek(-1, io.SEEK_CUR) field_id = decode_varint(stream) if field_id == 1: result["user_id"] = decode_varint(stream) elif field_id == 2: length = decode_varint(stream) result["username"] = stream.read(length).decode("utf-8") else: # Unknown field skipping for forward compatibility skip_length = decode_varint(stream) stream.read(skip_length) return resultencoded = serialize_record(1337, "network_worker")decoded = deserialize_record(encoded)assert decoded == {"user_id": 1337, "username": "network_worker"}
Key takeaways
- Binary serialization minimizes payload size and CPU cycles by avoiding ASCII parsing.
- Schema evolution requires assigning stable field tags and skipping unrecognized tags during deserialization.
- Zero-copy serialization designs allow reading fields directly from raw byte buffers without memory allocations.
Complexity
- Time: O(N) best, average, and worst case
- Space: O(N)
Both serialization and deserialization must inspect every field and byte of an object containing N total scalar components and nested elements, yielding strictly linear time complexity. Memory overhead is also O(N) to store the resulting byte array, formatted string, or reconstructed object graph.
Common mistakes
- Using untrusted deserializers like Python pickle or unconstrained XML parsers, which exposes applications to arbitrary remote code execution and entity expansion vulnerabilities.
- Assuming numeric precision is preserved identically across formats; for example, standard JSON numbers are double-precision floats, which can silently truncate 64-bit integers.
- Reusing or renumbering field tags across versions in binary schemas, breaking forward and backward compatibility.
- Neglecting circular object references, which triggers infinite loops and stack overflow exceptions during traversal.
Practice problems
- Nested dictionary to XML serializer (easy). Hint: Use recursion to transform child dictionaries into subelements and primitive values into tag text.
- Circular reference detector (medium). Hint: Maintain a set of visited object IDs during graph traversal and raise an exception if an ID is encountered twice.
- Zigzag integer encoder for signed varints (hard). Hint: Map negative numbers to positive odd values and positive numbers to even values before applying standard unsigned varint shifting.
Summary
Serialization converts in-memory objects into portable formats for disk and network transport. While text-based formats like JSON and XML offer readability and ubiquitous adoption, high-throughput distributed backends adopt binary formats with backward-compatible schema tags to maximize parsing speed and minimize payload overhead.
Finish the Prove step above to complete this lesson.
System Design Roadmap: From Beginner to Intermediate Architecture · 12 of 21
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!