Conceptintro
Data interchange format
Also called interchange format, serialization format, data serialization format, wire format, data format.
A data interchange format is an agreed layout of bytes for structured data, so that one program can write a value and another program, in any language, can read it back.
- Applies to
- core-languages
Idea
Two programs that share data must agree on how the data looks as bytes. A program holds a record as objects in its own memory, with pointers, padding and a byte order that belong to one machine and one language. Those bytes have no meaning to another process. A data interchange format is the agreement: it says how to write a value as a sequence of bytes (serialization) and how to read the bytes back into a value (deserialization). The OWASP cheat sheet defines serialization as "the process of turning some object into a data format that can be restored later"1.
JSON calls itself "a lightweight, text-based, language-independent data interchange format"2, and that phrase names the main questions to ask of any format. Is it text or binary? Is it tied to one language? Must the reader know a schema? Can a program read it one record at a time? Can a person edit it?
The example writes one record in five formats with only the Python standard library. Each format keeps a different part of the record.
import csv, io, json, pickle, struct
import xml.etree.ElementTree as ET
record = {"id": 42, "name": "Ada", "tags": ["admin", "ops"], "active": True}
# Text, self-describing: the field names travel with the data.
as_json = json.dumps(record, separators=(",", ":")).encode()
# Text, a table: CSV has no lists and no types, so the tags become one string.
buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=list(record), lineterminator="\n")
w.writeheader()
w.writerow({**record, "tags": ";".join(record["tags"])})
as_csv = buf.getvalue().encode()
# Text, a tree of elements.
root = ET.Element("user", id=str(record["id"]), active="true")
ET.SubElement(root, "name").text = record["name"]
for t in record["tags"]:
ET.SubElement(root, "tag").text = t
as_xml = ET.tostring(root)
# Binary, Python only.
as_pickle = pickle.dumps(record, protocol=5)
# Binary, the schema lives in the code: id (u32), active (bool), name (u8 length + bytes).
name = record["name"].encode()
as_struct = struct.pack("<I?B", record["id"], record["active"], len(name)) + name
for label, data in [("json", as_json), ("csv", as_csv), ("xml", as_xml),
("pickle", as_pickle), ("struct", as_struct)]:
print(f"{label:7}{len(data):4} bytes {data[:40]!r}")
# A round trip shows what each format keeps.
print(json.loads(as_json) == record)
print(next(csv.DictReader(io.StringIO(as_csv.decode()))))
print(ET.fromstring(as_xml).get("id"), type(ET.fromstring(as_xml).get("id")).__name__)
print(pickle.loads(as_pickle) == record)
uid, active, n = struct.unpack_from("<I?B", as_struct)
print(uid, active, as_struct[6:6 + n].decode())
json 59 bytes b'{"id":42,"name":"Ada","tags":["admin","o'
csv 42 bytes b'id,name,tags,active\n42,Ada,admin;ops,Tru'
xml 81 bytes b'<user id="42" active="true"><name>Ada</n'
pickle 71 bytes b'\x80\x05\x95<\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x02id\x94K*\x8c\x04name\x94\x8c\x03Ada\x94\x8c\x04tags'
struct 9 bytes b'*\x00\x00\x00\x01\x03Ada'
True
{'id': '42', 'name': 'Ada', 'tags': 'admin;ops', 'active': 'True'}
42 str
True
42 True Ada
JSON and pickle give back the same record. CSV and XML give back strings, so the reader must know that id is a number. The struct bytes are the smallest, because they hold no names and no types, but only a reader that knows the exact layout can decode them.
How it works
A format has two parts: a data model and an encoding. The data model is the set of values that the format can hold, for example objects, arrays, strings, numbers, true, false and null for JSON. The encoding is the rule that maps each value to bytes. A program maps its own types to the data model when it writes, and maps them back when it reads. Each mapping can lose information. JSON has no date type, CSV has no nested values, and a JSON number has no fixed size.
Text against binary. A text format writes values as characters, usually in UTF-8. A person can read it, a diff tool can compare two versions, and a text editor can change it. The cost is size and speed: the number 42 takes two characters, and a parser must scan every character for quotes and escapes. A binary format writes numbers in a fixed or variable-length integer encoding and puts the length before each string, so a reader can skip a field without scanning it. CBOR is a binary format "whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation"3. MessagePack says of itself that it "is an object serialization specification like JSON"4.
Self-describing against schema-based. In a self-describing format such as JSON, XML, CBOR or MessagePack, each record carries its field names and the type of each value, so a reader with no prior knowledge can build a tree. In a schema-based format, the writer and the reader share a schema, and the bytes hold only the values. XDR was an early example: "XDR uses implicit typing"5, and "The representation of all items requires a multiple of four bytes (or 32 bits) of data"5. Protocol Buffers and Avro use the same idea. The Protocol Buffers documentation says that a message cannot be fully interpreted "without access to its corresponding .proto file"6. The Avro specification says that "Binary encoded Avro data does not include type information or field names"7, and therefore "files or systems that store Avro data should always include the writer’s schema for that data"7.
A schema gives small messages, a check of the types, and generated code. It also needs a rule for change: a new reader must still read old data, and an old reader must still read new data. Avro lets a reader map the writer's schema to its own schema, and its specification says that this "facilitates both schema evolution as well as processing disparate datasets"7.
Language-neutral against language-specific. Some formats belong to one language. Python's pickle, Java object serialization, Go's gob and the V8 serializer of Node.js write the objects of their own runtime, with types that other languages do not have. The pickle documentation compares the two kinds: "JSON is interoperable and widely used outside of the Python ecosystem, while pickle is Python-specific"8. A language-specific format is convenient for a cache or for messages between two processes of the same program. It is the wrong choice for a public interface or for data that must outlive the program.
Streams of records. A program reads a single JSON document or XML document as one value, so the parser must see the end before the value is complete. A format for large data lets a program read one record at a time. CSV puts one record on each line9. JSON Lines puts one JSON value on each line, and its site calls it "a convenient format for storing structured data that may be processed one record at a time"10. Avro and other binary formats write a sequence of length-prefixed records in a container file.
Human editing. Configuration files are read by programs but written by people, so formats for them add comments and a lighter syntax. YAML is "a data serialization language designed to be human-friendly"11, and "TOML aims to be a minimal configuration file format that's easy to read due to obvious semantics"12.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Library | The C++ standard library has no data format. A program uses a library for each format. Alternative: A library such as nlohmann/json for JSON, pugixml for XML, or the C++ runtime of Protocol Buffers. |
| Java | Standard library | |
| C | Library | ISO C has no data format in its standard library. A program writes its own layout with fwrite and explicit byte order, or uses a library. Alternative: A library such as cJSON or Jansson for JSON, libxml2 for XML, or protobuf-c for Protocol Buffers. |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript runs on a JavaScript runtime and uses its JSON object. The static types are erased, so JSON.parse returns a value of type any and the program must check the shape itself. No example file exists, because the JavaScript example applies. |
| Go | Standard library | |
| Rust | Library | The Rust standard library has no data format. The serde framework separates the data structures from the formats, and crates such as serde_json, serde_cbor and quick-xml implement the formats. No example file exists; the JSON page has a serde_json example. Alternative: Serde with serde_json, or a crate for another format. |
| Kotlin | Library | The Kotlin standard library has no data format; on the JVM a program can use the XML and binary stream classes of Java, and the official kotlinx.serialization library adds JSON and other formats. No example file exists because kotlinc is not installed. Alternative: Kotlinx.serialization, or the classes of java.xml and java.io. |
| SQL | Native | The SQL standard defines JSON functions such as JSON_VALUE, JSON_QUERY and JSON_TABLE, and database systems add bulk load and export of CSV. A database stores rows in its own format, which is not an interchange format. |
| Bash | Library | Bash handles lines of text, so it can split simple delimited lines with read and IFS, but it has no parser for quoted CSV, JSON or XML. Alternative: The command-line tools jq for JSON and xmllint for XML. |
| PowerShell | Standard library | The cmdlets ConvertTo-Json, ConvertTo-Csv and ConvertTo-Xml, and ConvertFrom-Json and ConvertFrom-Csv, ship with PowerShell. No example file exists because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML is a document format, not a format for data records. A script element of type application/json can carry a JSON text inside a page. |
| CSS | Does not apply | Style sheets hold no data records to exchange. |
| Regular expressions | Does not apply | A regular expression can check one token, such as a number or a date, but it cannot parse the nested structure of JSON or XML. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | json, csv, xml.etree, tomllib (read only), plistlib and the Python-only pickle and marshal |
| JavaScript | native | the JSON object in the language; Node.js adds the binary v8.serialize |
| TypeScript | native | the JSON object of the JavaScript runtime; types do not survive JSON.parse |
| Java | stdlib | XML in the module java.xml; DataOutputStream and object serialization; no JSON in Java SE |
| Kotlin | library | the JVM classes of Java, or the official kotlinx.serialization library for JSON and other formats |
| C# | stdlib | System.Text.Json, System.Xml and XmlSerializer; BinaryWriter for a fixed layout |
| Go | stdlib | encoding/json, encoding/xml, encoding/csv and the Go-only encoding/gob |
| Rust | library | no format in std; the serde framework with crates such as serde_json |
| C | library | no format in the standard library; libraries for JSON, XML, CBOR and Protocol Buffers |
| C++ | library | no format in the standard library; libraries such as nlohmann/json and Protocol Buffers |
| Bash | library | text tools for CSV-like lines; jq for JSON |
| PowerShell | stdlib | ConvertTo-Json, ConvertTo-Csv, ConvertTo-Xml and the matching ConvertFrom cmdlets |
| SQL | native | JSON functions and types in the database; bulk load and export of CSV |
| Regex | n/a | a pattern can check a token but cannot parse nested data |
| HTML | n/a | a document format; a script element of type application/json can carry JSON |
| CSS | n/a | style sheets hold no data records |
Most languages read and write JSON with the standard library, and the languages that do not, such as C, C++ and Rust, have common libraries for it. Binary formats with a schema, such as Protocol Buffers and Avro, always need a library and a code generator or a schema parser. Python, Java, Go and JavaScript also have a binary format of their own runtime.
The standard libraries describe these tools in their own words. In Go, packages that implement the shared interfaces of encoding "include encoding/gob, encoding/json, and encoding/xml"13. The V8 serializer of Node.js writes values "in a way that is compatible with the HTML structured clone algorithm"14. The Java module java.xml "Defines the Java APIs for XML Processing (JAXP)"15, and DataOutputStream "lets an application write primitive Java data types to an output stream in a portable way"16. In .NET, System.Text.Json "provides functionality for serializing to and deserializing from (or marshalling and unmarshalling) JavaScript Object Notation (JSON)"17. Rust leaves formats to libraries, and "Serde is a framework for serializing and deserializing Rust data structures efficiently and generically"18. PowerShell converts objects to text with cmdlets, for example "The ConvertTo-Csv cmdlet returns a series of character-separated value (CSV) strings that represent the objects that you submit"19.
The example files show the same contrasts in other languages. JavaScript shows that JSON.stringify rejects a BigInt and turns a Date into a string and a Map into {}, while v8.serialize keeps all three. Go writes one struct as JSON, XML, CSV and gob, and shows that the first gob value carries its type. Java writes a record with DataOutputStream, reads the same bytes with the wrong layout, and writes XML with the DOM of the JDK. C# writes JSON with System.Text.Json, XML with XmlWriter and a fixed layout with BinaryWriter.
import datetime, json, pickle, plistlib
value = {"when": datetime.datetime(2024, 1, 15, 9, 30), "seen": {3, 1, 2}, "point": (1, 2)}
# pickle keeps the Python types, because it writes Python objects.
back = pickle.loads(pickle.dumps(value))
print(back == value, type(back["seen"]).__name__, type(back["point"]).__name__)
# json has no date, set or tuple type.
try:
json.dumps(value)
except TypeError as e:
print("json:", type(e).__name__)
# A default function picks a JSON form for each extra type, and the reader gets plain lists and strings.
def to_json(v):
if isinstance(v, datetime.datetime):
return v.isoformat()
if isinstance(v, set):
return sorted(v)
raise TypeError(type(v).__name__)
text = json.dumps(value, default=to_json, sort_keys=True)
print(text)
print(json.loads(text))
# plistlib writes the property lists of Apple systems, as XML or binary, and has a date type.
xml_plist = plistlib.dumps({"when": value["when"], "n": 1})
bin_plist = plistlib.dumps({"when": value["when"], "n": 1}, fmt=plistlib.FMT_BINARY)
print(len(xml_plist), len(bin_plist), bin_plist[:8])
print(plistlib.loads(bin_plist))
True set tuple
json: TypeError
{"point": [1, 2], "seen": [1, 2, 3], "when": "2024-01-15T09:30:00"}
{'point': [1, 2], 'seen': [1, 2, 3], 'when': '2024-01-15T09:30:00'}
276 68 b'bplist00'
{'n': 1, 'when': datetime.datetime(2024, 1, 15, 9, 30)}
- Verdict: stdlib. The standard library has
json,csv,xml.etree.ElementTree,plistlibandtomllib, and the Python-onlypickle.picklegives back adatetime, asetand atuple, because it writes Python objects.json.dumpsraisesTypeErrorfor the same value, so the program must choose a JSON form for each extra type withdefault, and the reader then gets lists and strings.plistlibwrites the same dictionary as an XML property list or as a much smaller binary one that starts withbplist00.
import java.io.*;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] args) throws Exception {
int id = 42;
String name = "Ada";
boolean active = true;
// Binary: the bytes have no names and no types. The reader must know the layout.
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
out.writeInt(id);
out.writeUTF(name);
out.writeBoolean(active);
}
byte[] bin = bytes.toByteArray();
StringBuilder hex = new StringBuilder();
for (byte b : bin) hex.append(String.format("%02x ", b));
System.out.println(bin.length + " bytes: " + hex.toString().trim());
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bin))) {
System.out.println(in.readInt() + " " + in.readUTF() + " " + in.readBoolean());
}
// The same bytes read with a different layout give a wrong value and no error.
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bin))) {
System.out.println("read as a long: " + in.readLong());
}
// Text: XML with the JDK's own DOM and transformer.
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element user = doc.createElement("user");
user.setAttribute("id", Integer.toString(id));
user.setAttribute("active", Boolean.toString(active));
user.appendChild(doc.createElement("name")).setTextContent(name);
doc.appendChild(user);
var t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter sw = new StringWriter();
t.transform(new DOMSource(doc), new StreamResult(sw));
String xml = sw.toString();
System.out.println(xml.getBytes(StandardCharsets.UTF_8).length + " bytes: " + xml);
Document back = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
Element root = back.getDocumentElement();
System.out.println(root.getAttribute("id") + " " + root.getElementsByTagName("name").item(0).getTextContent());
}
}
10 bytes: 00 00 00 2a 00 03 41 64 61 01
42 Ada true
read as a long: 180388839780
51 bytes: <user active="true" id="42"><name>Ada</name></user>
42 Ada
- Verdict: stdlib. Java SE has XML in the module
java.xmland binary streams injava.io, but no JSON API.DataOutputStreamwrites anintas four big-endian bytes and a string withwriteUTFas a two-byte length and the bytes, so the record takes 10 bytes with no names. When a reader uses the wrong layout,readLongtakes the first eight bytes and gives a wrong number with no error. The DOM and theTransformerof the JDK write the XML, and the output has the attributes in name order, not in the order of the code.
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Xml;
var user = new User(42, "Ada", ["admin", "ops"]);
// JSON: text, self-describing, with the source generator of System.Text.Json.
string json = JsonSerializer.Serialize(user, AppJson.Default.User);
Console.WriteLine($"json {Encoding.UTF8.GetByteCount(json)} {json}");
User back = JsonSerializer.Deserialize(json, AppJson.Default.User)!;
Console.WriteLine($"{back.Id} {back.Name} {string.Join(",", back.Tags)}");
// XML: text, written element by element with XmlWriter.
var sb = new StringBuilder();
using (var w = XmlWriter.Create(sb, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
w.WriteStartElement("user");
w.WriteAttributeString("id", user.Id.ToString());
w.WriteElementString("name", user.Name);
foreach (string t in user.Tags) w.WriteElementString("tag", t);
w.WriteEndElement();
}
Console.WriteLine($"xml {sb.Length} {sb}");
// Binary: BinaryWriter writes a fixed layout. Only the code knows the field order.
var ms = new MemoryStream();
using (var bw = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true))
{
bw.Write(user.Id);
bw.Write(user.Name);
bw.Write(user.Tags.Length);
foreach (string t in user.Tags) bw.Write(t);
}
byte[] bin = ms.ToArray();
Console.WriteLine($"bin {bin.Length} {Convert.ToHexString(bin)}");
ms.Position = 0;
using var br = new BinaryReader(ms);
int id = br.ReadInt32();
string name = br.ReadString();
string[] tags = new string[br.ReadInt32()];
for (int i = 0; i < tags.Length; i++) tags[i] = br.ReadString();
Console.WriteLine($"{id} {name} {string.Join(",", tags)}");
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(User))]
partial class AppJson : JsonSerializerContext;
record User(int Id, string Name, string[] Tags);
json 45 {"id":42,"name":"Ada","tags":["admin","ops"]}
42 Ada admin,ops
xml 67 <user id="42"><name>Ada</name><tag>admin</tag><tag>ops</tag></user>
bin 22 2A00000003416461020000000561646D696E036F7073
42 Ada admin,ops
- Verdict: stdlib.
System.Text.Jsonwrites the record as JSON, here with a source-generated context and camel-case names, and reads it back.XmlWriterwrites XML one element at a time.BinaryWriterwrites anintas four little-endian bytes and a string as a length byte and the UTF-8 bytes, so the record takes 22 bytes, against 45 for the JSON. The hex dump has no field names: the reader must callReadInt32,ReadStringandReadInt32in the same order as the writer.
const v8 = require("node:v8");
const record = {
id: 42,
name: "Ada",
joined: new Date(Date.UTC(2024, 0, 15)),
roles: new Map([["admin", true]]),
big: 2n ** 64n,
note: undefined,
};
// JSON is text, and every JSON parser can read it, but it has fewer types.
let text;
try {
text = JSON.stringify(record);
} catch (e) {
console.log("JSON:", e.constructor.name);
}
const plain = { ...record, big: record.big.toString() };
text = JSON.stringify(plain);
console.log(text.length, text);
const back = JSON.parse(text);
console.log(typeof back.joined, back.roles, "note" in back);
// v8.serialize is binary and keeps Date, Map and BigInt, but only V8 can read it.
const bin = v8.serialize(record);
// The first byte is the version tag 0xff of the V8 format.
console.log(Buffer.isBuffer(bin), bin[0].toString(16));
const again = v8.deserialize(bin);
console.log(again.joined instanceof Date, again.roles.get("admin"), again.big, "note" in again);
JSON: TypeError
98 {"id":42,"name":"Ada","joined":"2024-01-15T00:00:00.000Z","roles":{},"big":"18446744073709551616"}
string {} false
true ff
true true 18446744073709551616n true
- Verdict: native.
JSON.parseandJSON.stringifyare part of the language.JSON.stringifythrows aTypeErrorfor aBigInt, writes aDateas an ISO string, writes aMapas{}and drops a property whose value isundefined. The parsed value has a string where theDatewas. The Node.js modulenode:v8writes the binary format of the V8 engine, which keepsDate,Map,BigIntandundefined, but only V8 can read it, and its documentation says that equal values can give different bytes.
package main
import (
"bytes"
"encoding/csv"
"encoding/gob"
"encoding/json"
"encoding/xml"
"fmt"
"strconv"
"strings"
)
type User struct {
XMLName xml.Name `json:"-" xml:"user"`
ID int `json:"id" xml:"id,attr"`
Name string `json:"name" xml:"name"`
Tags []string `json:"tags" xml:"tag"`
}
func main() {
u := User{ID: 42, Name: "Ada", Tags: []string{"admin", "ops"}}
j, _ := json.Marshal(u)
x, _ := xml.Marshal(u)
var c bytes.Buffer
w := csv.NewWriter(&c)
w.Write([]string{"id", "name", "tags"})
w.Write([]string{strconv.Itoa(u.ID), u.Name, strings.Join(u.Tags, ";")})
w.Flush()
// gob is binary and Go only. The first value on a stream also carries its type.
var g bytes.Buffer
enc := gob.NewEncoder(&g)
enc.Encode(u)
first := g.Len()
enc.Encode(u)
fmt.Println("json", len(j), string(j))
fmt.Println("xml ", len(x), string(x))
fmt.Println("csv ", c.Len(), strings.ReplaceAll(c.String(), "\n", `\n`))
fmt.Println("gob ", first, "then", g.Len()-first)
var back User
gob.NewDecoder(&g).Decode(&back)
fmt.Printf("%+v\n", back.Tags)
// Without a Go type, a JSON number becomes float64.
var any map[string]interface{}
json.Unmarshal(j, &any)
fmt.Printf("%T %T\n", any["id"], any["tags"])
}
json 45 {"id":42,"name":"Ada","tags":["admin","ops"]}
xml 67 <user id="42"><name>Ada</name><tag>admin</tag><tag>ops</tag></user>
csv 30 id,name,tags\n42,Ada,admin;ops\n
gob 144 then 25
[admin ops]
float64 []interface {}
- Verdict: stdlib. The packages
encoding/json,encoding/xmlandencoding/csvwrite the same struct as text, with struct tags that name the fields of each format. CSV has no list, so the program joins the tags itself. The Go-onlyencoding/gobis binary: the first value on a stream also carries a description of its type, so it takes 144 bytes, and the second value of the same type takes only 25. Without a Go type,json.Unmarshalgives afloat64for a number and[]interface {}for an array.
Variations and related ideas
- Interchange against storage. An interchange format moves data between programs. A storage format, such as the file format of a database, is read by one program and can change between versions of that program.
- Canonical forms. Many formats allow more than one encoding of the same value, for example with keys in a different order or with extra spaces. A canonical form fixes one encoding, so that two programs can compare or sign the bytes.
- Schemas for self-describing formats. JSON Schema and the XML schema languages add a schema to a format that does not need one, for validation and documentation.
- Object serialization. A language runtime can write an object graph with its types and references, see Serialization. This is the language-specific end of the range.
Pitfalls
- Untrusted input to a language-specific format. "The pickle module is not secure. Only unpickle data you trust."8 The same risk applies to other formats that rebuild objects of any class, such as Java object serialization, see Deserialization of untrusted data. Use a data-only format such as JSON for input from outside.
- Large integers in JSON. JSON does not limit the size of a number, but many parsers read numbers as IEEE 754 doubles. RFC 8259 notes that "good interoperability can be achieved by implementations that expect no more precision or range than these provide"2. An identifier above 2^53 can change in JavaScript. Send large identifiers as strings.
- Types that do not exist in the format. Dates, decimal numbers, binary data, sets and maps with non-string keys have no JSON type. Agree on a string form, for example an ISO 8601 date, and document it.
- Split CSV on commas. A field can hold a comma, a quote or a line break inside quotes9. Use a CSV parser, not a split on
,. - Character encoding. A text format is only text after the reader knows the encoding. Write UTF-8, and say so in the format or the protocol.
- Schema changes. A schema-based reader with an old schema can read new data wrongly with no error, as the Java example shows. Change a schema only in ways that old readers can handle, and keep the writer's schema with the data, as Avro does7.
- Whole-message limits. The Protocol Buffers documentation warns: "For data that exceeds a few megabytes, consider a different solution"6. A format that the reader must load as one value is a bad fit for large data sets. Use a stream of records.
Cost
The size and the speed of a format depend on the data and on the library more than on the format alone, so measure with your own data. Some general rules hold. A self-describing format repeats each field name in each record, and a schema-based format does not, so the schema-based form of many small records is smaller. A text format must convert each number from digits and scan each string for escapes. A binary format with a length before each string lets a reader skip fields. Compression such as gzip removes much of the repeated field names in a text format, at the cost of CPU time. Protocol Buffers "Messages are not compressed"6, so a large message is often compressed before it is sent.
The cost that matters most is often not speed but change. A format with a public specification and many parsers is cheap to keep for years. A format that only one language or one version of a library can read becomes a cost when the program changes.
History
Programs exchanged binary records long before standard formats, with each pair of programs agreeing on its own layout. In June 1987, Sun Microsystems published XDR as RFC 1014, "a standard for the description and encoding of data"5 that Sun RPC and NFS used. The RFC compares XDR with "X.409, ISO Abstract Syntax Notation"5. CBOR still names "ASN.1 and MessagePack"3 as earlier binary serializations.
According to Wikipedia, the W3C published XML 1.0 as a Recommendation in 199820. Douglas Crockford and Chip Morningstar sent the first JSON message in 200121. RFC 8259 is the current IETF specification of JSON2. The OWASP cheat sheet sums up the change: "Today, the most popular data format for serializing data is JSON. Before that, it was XML."1
Binary formats with schemas came back at a large scale. Google used Protocol Buffers inside the company, and "Protobuf was open sourced in 2008"6. Avro7 and the schemaless MessagePack4 and CBOR3 are other binary formats, and CBOR is an Internet Standard of the IETF (STD 94)3. For configuration, YAML11 and TOML12 are text formats that people can write by hand.
References
- RFC 8259, the JSON standard, with its notes on the interoperability of numbers2.
- RFC 8949, CBOR, a binary format with the data model of JSON and more3.
- RFC 1014, XDR, an early schema-based binary format5.
- The Protocol Buffers overview and the Avro specification, two schema-based binary formats67.
- The pickle documentation, for a language-specific format and its security warning8.
- The OWASP Deserialization Cheat Sheet1.
- OWASP Cheat Sheet Series, Deserialization Cheat Sheet, What is Deserialization
- T. Bray (Ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format, December 2017, the abstract; 6 Numbers
- C. Bormann, P. Hoffman, RFC 8949: Concise Binary Object Representation (CBOR), December 2020, the abstract
- MessagePack specification, the introduction
- Sun Microsystems, RFC 1014: XDR, External Data Representation Standard, June 1987, 1 Introduction; 2 Basic Block Size
- Protocol Buffers Documentation, Overview, the introduction; When are Protocol Buffers not a Good Fit; Protobuf Open Source Philosophy
- Apache Avro 1.12.0 Specification, Data Serialization and Deserialization
- The Python Standard Library, pickle, Python object serialization, the warning at the top; Comparison with json
- Y. Shafranovich, RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, October 2005, 2 Definition of the CSV Format
- JSON Lines, the introduction
- YAML Ain't Markup Language (YAML) version 1.2.2, October 2021, Chapter 1 Introduction to YAML
- TOML: Tom's Obvious Minimal Language, v1.0.0, Objectives
- Go standard library, package encoding, the overview
- Node.js documentation, V8, Serialization API, Serialization API; v8.serialize
- Java SE 25 API, module java.xml, the module description
- Java SE 25 API, java.io.DataOutputStream, the class description
- .NET documentation, JSON serialization and deserialization in .NET, the overview
- Serde, the overview, the first paragraph
- PowerShell documentation, ConvertTo-Csv, Description
- XML, Wikipedia, the introduction
- Douglas Crockford, The JSON Saga (transcript of the talk), the first message
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 7GXT8V Edit this page History Report an error Markdown