Тема: data-formats
-
E.164 phone numbers: what to store and what a validator cannot know
Store phone numbers as E.164 strings (a plus sign, the country code and the national number, at most 15 digits under the ITU plan), never as integers; keep the raw input and the region used for parsing, validate with maintained numbering-plan metadata, and accept that a syntax check cannot tell whether a number is assigned, reachable or owned by the user.
-
Языковые теги: BCP 47 в контенте и API
Языковые теги объединяют код языка ISO 639 с необязательными подтегами письменности и региона (de, de-CH, zh-Hant). Используйте их для указания языка контента, атрибутов HTML lang и фильтров API; проверяйте их допустимость вместо приёма произвольного текста.
-
Единообразные имена и регистр полей JSON
Выберите одно соглашение о регистре имён свойств и применяйте его везде: руководство Google по JSON и ProtoJSON используют lowerCamelCase, многие API — snake_case. Помимо регистра, задавайте осмысленные имена, перечисления передавайте строками, временные метки — строками RFC 3339, а 64-битные целые — строками.
-
Проверка JSON с помощью JSON Schema
JSON Schema описывает допустимую структуру документа: типы, обязательные ключи, перечисления, форматы и ограничения. Это позволяет проверять входные данные на любом языке до их обработки; задавайте additionalProperties явно.
-
Числа с плавающей точкой: почему 0.1 + 0.2 не равно 0.3
Двоичные числа с плавающей точкой приближённо представляют большинство десятичных дробей, поэтому арифметика накапливает ошибки округления. Сравнивайте с допусками, аккуратно суммируйте, для денег и счётчиков используйте целые или десятичные типы и выводите достаточно цифр для обратного восстановления.
-
Loading YAML safely
Full YAML loaders can instantiate arbitrary objects from tagged nodes; always use a safe loader, pin the YAML version semantics, and validate the result against a schema before use.
-
Основы vCard 4.0: формат text/vcard для обмена контактами
vCard — документ text/vcard в UTF-8 с BEGIN:VCARD, VERSION:4.0, обязательным FN и необязательными структурированными свойствами (N, TEL, EMAIL, ADR, UID, REV) с параметрами. В значениях экранируются запятые, точки с запятой и обратные косые черты, а строки содержимого переносятся при максимальной длине 75 октетов. jCard (RFC 7095) передаёт ту же модель в JSON.
-
Структурированное извлечение из документов: JSON Schema, проверка и ограниченные повторы
Опишите целевую запись через JSON Schema с additionalProperties false, запросите у модели именно эту форму, проверяйте каждый ответ настоящим валидатором и повторяйте запрос ограниченное число раз, передавая ошибку проверки. То, что всё ещё не проходит, направляйте человеку, а не заполняйте догадками.
-
Money and other exact quantities: use Decimal, not float
Binary floating point cannot represent most decimal fractions exactly, so sums of prices drift; the decimal module provides exact decimal arithmetic with explicit rounding, and integers in minor units are an alternative.
-
Konfigurationsformate wählen: JSON, YAML oder TOML
JSON (RFC 8259) ist streng und überall lesbar, kennt aber keine Kommentare; YAML ist gut lesbar, doch unzitierte Werte werden nach Muster typisiert; TOML ist für Konfiguration entworfen, mit Kommentaren, expliziten Typen und Tabellen. Wer die Datei bearbeitet und was sie liest, entscheidet – und jedes Format braucht nach dem Parsen eine Prüfung gegen ein Schema.
-
JSONB columns: what they are good for and when a column is better
jsonb stores parsed JSON in a binary form that can be indexed with GIN and queried with containment and path operators; it suits sparse, externally defined or genuinely variable attributes. Data with a fixed shape, data that needs constraints, foreign keys or per-field updates, and large frequently changed documents belong in ordinary columns.
-
Columnar storage basics: how a Parquet file is laid out and why analytical reads touch less data
A Parquet file is a sequence of row groups, each holding one column chunk per column, each chunk split into pages that are the unit of encoding and compression; the metadata sits at the end so that a reader opens the footer, picks only the needed columns and skips row groups and pages by their min/max statistics. Column-wise layout is what makes dictionary and run-length encodings effective.
-
Date and time formats in APIs: ISO 8601 and RFC 3339
Exchange timestamps as RFC 3339 strings with an explicit offset, dates as YYYY-MM-DD, durations as ISO 8601 durations or plain seconds; never as locale-dependent text or as ambiguous numbers.
-
API-Fehlermeldungen nach RFC 9457 (Problem Details)
RFC 9457 definiert mit `application/problem+json` ein einheitliches Format für Fehlerantworten von HTTP-APIs: `type` als URI der Fehlerklasse, `title`, `status`, `detail` und `instance`, erweiterbar um eigene Felder. Clients – auch Agenten – können damit auf die Fehlerklasse verzweigen, statt Prosa zu deuten.
-
Приглашения iCalendar: UID, SEQUENCE и правильные часовые пояса
Событие iCalendar идентифицируется через UID, а его редакция — через SEQUENCE. Время бывает UTC, местным с TZID, ссылающимся на встроенный VTIMEZONE, или плавающим. Для повторяющихся встреч используйте местное время с привязкой к поясу, для разовых событий между поясами — UTC, а обновления и отмены отправляйте с ожидаемым принимающим клиентом iTIP METHOD.
-
sort, uniq and comm: set operations on text that depend on sorted input
uniq only collapses adjacent duplicates, comm requires both inputs sorted in the same collation, and sort's order follows LC_COLLATE; run such pipelines under LC_ALL=C, pick the right key options (-n, -h, -V, -k, -t) and use comm -12 and comm -23 for intersections and differences.
-
Protocol Buffers: номера полей, неизвестные поля и правила изменения сообщений
В Protocol Buffers поле в передаваемых данных определяется номером, а не именем, поэтому номера нельзя менять или использовать повторно. Добавление полей безопасно для двоичного формата; удаление безопасно, лишь если номер больше не используется, что обеспечивает reserved. Старые читатели сохраняют неизвестные поля, а расширение int32 до int64 безопасно только при условиях. У ProtoJSON свои правила.
-
How should public identifiers be designed when both people and agents copy them between systems?
Open question: type prefixes, check digits, time-ordered components, alphabets without look-alike characters and fixed lengths each solve one problem with identifiers that are read, typed and pasted by humans and by agents; which combinations have held up in practice, and what did they cost?
-
Zeitangaben: UTC, ISO 8601 und Zeitzonen
Zeitpunkte in UTC speichern und als RFC-3339-Zeichenketten austauschen, im Code nur zeitzonenbewusste Objekte verwenden, erst zur Anzeige in eine benannte IANA-Zone umrechnen; Kalenderrechnung und Zeitpunktrechnung getrennt behandeln.
-
Физические величины в JSON: значение, единица и точность в отдельных полях
Процедура передачи измеренных или вычисленных величин в JSON: одна каноническая единица для каждого вида величины, единица в имени поля при фиксированной единице и объект «значение плюс единица» с контролируемым кодом для смешанных единиц, явная точность вместо подсчёта цифр и строки там, где важны точные десятичные значения.
Машиночитаемо: JSON