A Document in a Cell: Objects, Arrays, and Values
Chapter 1 — “JSON in a Cell”
The Sorting Bay is behind you now. The neighboring compartment on the station's Intake Level is called the Unpacking Bay: long racks line the walls, with parcels stacked on the shelves. That's what they call the second part of the first signal here. Along with the Kotomarket database and the raw text came service messages exchanged by the store's machines during the final two weeks before the Great Severance, from February 10 through February 24, 2025.
The machines had plenty to say. The mobile app reported every tap: viewing a product, adding it to the cart, placing an order. The payment gateway sent long responses back to the store. Product cards held attributes that didn't have their own columns, while customer settings lived in separate documents. Curly braces appeared almost everywhere.
The commandant gives you the assignment in two lines. He needs a summary of the store's final two weeks: what people bought, how many orders there were, and how they paid.
You open the first parcel, event 3 from the app_events table. Four columns, nothing unusual at first glance: an ID, a timestamp, and the purchase type. But the fourth column, payload, contains an entire order. It has the customer and their city, two items with prices, an empty coupon list, and the total. To the table, that's one cell. Inside it is a whole tree.
QUERY: Think of a table as a cabinet with shelves, and as a box with more boxes inside. For now, the task is simple: figure out what's where and what gets lost if we rearrange the contents.
We won't extract individual values yet. We'll take one of these cells apart and study its structure: where the object is, where the array is, what types the individual values have, and exactly what PostgreSQL does to the original text when it turns it into a document.

What a document is made of
Consider a simpler event. Event 1 is a view of Wireless Headphones, and its payload fits on one line. PostgreSQL prints it like this:
{"app": "4.6.0", "user": {"id": 23, "city": "Tampa"}, "price": 59.90, "product_id": 1, "schema_version": 2}
Curly braces enclose an object. Inside are comma-separated “key: value” pairs. A key is always a string in double quotes: "app", "price", "product_id". Values can have different types. "4.6.0" is a string, so it also appears in double quotes. 59.90 has no quotes: it's a number. The value of the "user" key is more complex—another object with the keys id and city. It's a box inside a box.
Now return to the order from the opening scene, event 3. It has a key named "items", whose value starts with a square bracket: [{...}, {...}]. Square brackets mark an array—an ordered, comma-separated list of values. Array elements don't have keys, but they do have positions: first, second, and so on. In order 5001, the items array contains two item objects, Wireless Headphones and Basic T-Shirt. Next to it is "coupons": []. This is another array, but an empty one: the order had no coupons.
A value with no nested objects or arrays is called a scalar. has four kinds of scalars:
- a string in double quotes:
"Tampa"; - a number without quotes:
59.90,1.2,-3; - a Boolean value,
trueorfalse(the Wireless Headphones product card contains"wireless": true); null, meaning “nothing.”
Those are the only scalar types in JSON. JSON, for example, has no separate date type: a timestamp has to be stored as a string or as a number of seconds. The format doesn't allow single quotes or comments either. Beyond that, these few building blocks can be nested inside one another to any depth.
JSON stands for JavaScript Object Notation. The notation grew out of JavaScript object syntax, and in the early 2000s Douglas Crockford described it as a standalone data-interchange format. Today, web services send JSON constantly, so seeing it in a database is common.
Where JSON shows up at work
The parcels came from five places. Sources like these are common in application databases.
app_events.payload — mobile app events. The set of properties depends on the event, so developers don't create a separate column for every field. A product view only needs the product and price, while placing an order also needs the items, coupons, and total.
payments.response — payment gateway responses. It's an external API, and the store doesn't control which fields may appear tomorrow. So it makes sense to save the whole response exactly as the gateway sent it, then extract the fields you need later.
product_cards.attrs — product attributes. A book has a page count and publication year, headphones have battery information and colors, and a coffee maker has a power rating. If you create a column for every possible attribute, the table quickly becomes unwieldy, so properties like these are often stored in a document.
user_settings.settings — customer settings: theme, mailing preferences, notifications, experiment flags. The app adds a new setting, and another key appears without a separate table .
raw_inbox.body — the incoming stream from the final evening: webhooks, imports, messages from partners and the support bot. This is a real raw-data inbox: incoming data is stored here without validation.
In other projects, I've most often seen in responses from external APIs. A team saves the entire response “just in case,” and six months later it turns out that one rare field from it really was needed.
The cell below selects one document from each table and shows the type of the column that stores it. The documents are cast to text so all five rows can fit into one doc column and PostgreSQL can display them as text. Before you run the cell, make a prediction: in four tables, the document column has the type jsonb. What do you expect to see for raw_inbox.body, where data is stored without validation?
An indented document: jsonb_pretty
The payment row in the previous output stretches far to the right. With text like that, you quickly lose track of where a nested object ends and which level the next key belongs to.
PostgreSQL provides jsonb_pretty for this. The function prints a document in an indented layout: each key goes on a separate line, and each level of nesting shifts four spaces to the right. It takes jsonb as input and returns ordinary text.
Use the order from the opening scene. Before you run the query, use the structure above to count the depth of the longest branch: the outer object, then items, then one item. Also try to predict what the empty coupons array will look like in this indented form.
Open the next document without the diagram this time. Take payment 2, the declined payment from the overview, and before you run the query find three things: how deep the customer's city is, how many elements are in the charges array, and where the gateway stored the reason for the decline.
What type is a value? jsonb_typeof
In raw_inbox, the body column has the type text. PostgreSQL sees only characters there, so there is no value for JSON functions to work with yet. You can turn the text into a document with a cast: body::jsonb, or with the full form CAST(body AS jsonb). At that point PostgreSQL parses the string according to JSON rules and builds a tree of values.
After the cast, you can ask the database what it produced. The jsonb_typeof function returns one of six words: object, array, string, number, boolean, or null.
But the raw stream has a problem: data was written there without validation, so some rows aren't JSON at all. If you cast the whole column to jsonb immediately, the query stops at the first bad row:
SELECT msg_id, jsonb_typeof(body::jsonb) AS kind
FROM raw_inbox;
ERROR: invalid input syntax for type json
DETAIL: The input string ended unexpectedly.
The first problem is message 7, which is empty. Of the twelve messages, seven contain valid JSON: messages 1 through 6 and message 10. In Chapter 5, we'll build a check that can find rows like these without making the query fail. For now, we'll list the seven known message IDs explicitly.
First, make a prediction. Messages 1 and 2 start with a curly brace, so they're objects. Message 3 starts with a square bracket, so it's an array. That leaves messages 4, 5, and 6. Pay special attention to message 4: its entire text is enclosed in double quotes.
[], 42, "hello", and null are JSON too
This is a common source of mistakes if you're used to seeing only in API responses. APIs usually return an object and, less often, an array, so it's easy to pick up a false rule over time: JSON must have curly or square brackets.
Under the current JSON standard, RFC 8259, any value can appear at the top level: a number, string, true, false, or null. The older RFC 4627 specification from 2006 really did require an object or an array. That's where the rule that still appears in code and conversations came from. PostgreSQL follows the modern definition and accepts scalars.
Message 4 shows this especially clearly. The sender turned an object into text, then wrapped that text once more as a JSON string. This has a name: double serialization. I've seen it more than once in webhooks. There really is a document inside the string, but PostgreSQL currently treats the whole value as one string with no accessible keys.
Message 6 has a different trap. The cell contains four characters: n, u, l, l. After ::jsonb, they become the JSON value null. SQL NULL works differently: the body column is declared NOT NULL, and this particular cell is definitely populated. We'll return to the difference between these two kinds of “nothing” in the third lesson of this chapter.
Now test this with a few short . There are six rows below: we cast each one to jsonb, then ask for its type. Before you run the query, mark which rows you think will work. Decide separately what happens to 'null': will it produce an error, SQL NULL, or a third kind of value?
null. What will SELECT body IS NULL FROM raw_inbox WHERE msg_id = 6 return?text, json, jsonb: three ways to store a document
PostgreSQL can store the same in three different ways. With a short document, the difference is barely noticeable. But as soon as you start reading fields, comparing documents, or processing a raw stream, the type affects the result.
text stores nothing but characters and doesn't check whether those characters form valid JSON. That's why an empty string, a complaint about a courier, and JSON followed by OK can all live side by side in raw_inbox.body. To treat that content as a document later, you'll have to cast it explicitly.
json validates the syntax when the value is written, then preserves the original text character for character: spaces, key order, and even duplicate keys remain in place. When you read a field, PostgreSQL parses the stored text again.
jsonb parses the document when it's written and stores the resulting tree in binary form. Reading fields is faster, documents can be compared, and you can build indexes for searching them—we'll get to indexes in Chapter 6. But after storing a value this way, you can't reconstruct the original string. Extra spaces disappear, the database prints keys in its own order, and if a key is repeated, only its last value survives.
PostgreSQL's documentation recommends jsonb for most application use cases. json is less common, for example when you need to preserve the original key order. In our , the four columns that hold parsed documents use the type jsonb.
Take a string where the differences are deliberately easy to see. After 18, there are three spaces in a row, the key qty appears twice, and product_id comes first. The spaces are added with repeat(' ', 3): the function repeats a space three times, and || joins the pieces of the string. That makes the exact number of spaces visible right in the query. Before you run it, try to predict what text will appear in each of the three columns after the casts.
Both as_json and as_jsonb end with ::text. That turns all three results into ordinary text, so you can compare them character by character exactly as PostgreSQL returns them.
json preserves the original representation, including both status keys. After conversion to jsonb, only the final status remains, and the document itself is stored as a tree.A duplicate key in a real message
The previous was deliberately constructed for the experiment, but duplicate keys also appear in real data. A partner sent message 10 at 23:44. It starts with status set to "queued", followed by a data object with the event, and then ends with status again, this time set to "sent". It looks as though the partner's system appended the new status to the end of the document without removing the old one.
The standard doesn't explicitly forbid this representation, but it warns that programs may handle duplicate keys differently. PostgreSQL behaves predictably with its two types: json preserves both values, while jsonb keeps the last one.
Before you run the query, record your prediction. Which status will remain in as_jsonb? How many times will status appear in as_json? And look at the order: which key will PostgreSQL print first in as_jsonb?
silently loses duplicate keys
If the sequence of values carries meaning—first queued, then sent—you can't reconstruct it after writing the document to jsonb. Even json returns the last value when you access a field: reading the status field from message 10 will also return sent (we'll start reading fields in the next lesson). The first status can only be seen in the preserved original representation.
When a response from an external system may later be needed for an incident investigation, I store the original separately as text or json and keep a jsonb copy alongside it for queries. This is especially useful with webhooks: the signature is often calculated over the exact bytes of the request body, and after conversion to jsonb, those bytes are gone. In Chapter 5, we'll learn how to find documents with duplicate keys in advance.
Key order and whitespace
We've already caught jsonb reordering keys twice. In the lesson , qty ended up before product_id. In the order from the opening scene, schema_version was printed at the very bottom even though it came first in the original event. The reason is jsonb's internal representation: PostgreSQL stores object keys in its own order and prints them in that same order. Here, shorter keys in bytes come first, and keys of the same byte length are ordered byte by byte. The documentation doesn't guarantee this order, so don't build logic around it.
The original whitespace isn't preserved either. When PostgreSQL prints jsonb, it inserts one space after each colon and comma regardless of how many spaces were present in the input string.
Below are three messages from the raw stream: the original text on the left and the result after conversion to jsonb on the right. Before you run it, try to predict what will change. In message 1, the keys are written as event, user_id, product_id. In message 2, event comes first, followed by user. Message 3 is different: it's an array of two objects. Think separately about whether PostgreSQL is allowed to reorder the elements of the array itself.
Comparing documents by content
Now it's clear why comparing as ordinary text is risky. Two documents can contain the same keys and values but differ in whitespace or key order. A string comparison with = treats them as different. Comparing two jsonb values checks their content and, in that case, returns true.
Two details are easy to forget. In an array, element order is part of the content, so [6, 7] and [7, 6] are not equal. Value type matters too: the number 12.90 is different from the string "12.90", even though the digits look the same to us.
The json type has no equality operator at all. The query body::json = body::json fails with the error operator does not exist: json = json, while trying to use DISTINCT or GROUP BY on json gives could not identify an equality operator for type json. For documents you need to compare or group, jsonb is much more convenient.
There are three pairs below, and we'll compare each pair twice: once as text and once as jsonb. You can solve the first pair immediately. The keys and values are the same; only their order and whitespace differ, so same_text will be false and same_jsonb will be true. For the second and third pairs, write down your answer first, then click “Run.”
Here's the final task for the lesson. An integrator writes to Kotomarket support: “We sent you the webhook {"product_id":12,"event":"cart","user":{"id":23}}. Did it arrive?” The analyst on duty compared the supplied text with every valid message and answered no.
The query below runs without errors, but all seven rows produce false. Before you change anything, look through the raw stream and find the message whose content matches the integrator's document.
same_doc compares the strings character by character. If two documents contain the same information but use a different key order or different whitespace, the strings won't match. Change only the comparison so it checks the documents' content. Don't touch the message list, columns, or sorting: the result must still contain seven rows, with true appearing exactly once.Common mistakes
Assuming JSON must be an object
Row: message 5, text 42.
Expectation: there are no brackets or keys, so this probably isn't .
A quick check disproves that assumption: jsonb_typeof(body::jsonb) returns number. JSON doesn't require an object at the top level. In our raw stream, four valid messages have other top-level types: message 3 is an array, message 4 is a string, message 5 is a number, and message 6 is null.
What to do: before you analyze a column, count its top-level types. If you find anything besides object, one query applied to every row may give the wrong result.
Confusing JSON null with SQL NULL
Row: message 6, text null.
Expectation: body IS NULL will find it.
Run the check. The result is false. The cell contains four letters that become the JSON value null after the cast. SQL NULL means something different: there is no value in the cell itself.
What to do: for JSON null, jsonb_typeof returns the string null; for a real SQL NULL, the result is SQL NULL itself. We'll examine this pair more closely in the third lesson.
Casting the entire raw column to jsonb
Row: message 7, with empty text.
Expectation: body::jsonb will parse the good rows and return NULL for garbage.
In practice, the entire query fails with invalid input syntax for type json. A cast doesn't silently skip a bad row: the first error stops execution.
What to do: for now, cast only rows you already know contain valid JSON. In Chapter 5, we'll build a safe check for the entire column.
Expecting jsonb to preserve the original representation
Row: message 10, with status appearing twice.
Expectation: after ::jsonb, the document will remain exactly as the partner sent it.
Instead, "queued" disappears and the keys are printed in a different order. jsonb stores the parsed content and no longer remembers the original string.
What to do: if you need the original representation for an audit, webhook signature, or investigation of another system's error, store it separately as text or json.
Comparing documents as strings
Row: message 2 and the integrator's document.
Expectation: identical content should produce identical strings.
Here the key order and whitespace differ, so ordinary = returns false.
What to do: compare jsonb with jsonb. [6, 7] and [7, 6] will still remain different, as will the number 12.90 and the string "12.90".
Transfer: your first look at a JSON column
When I open an unfamiliar column of documents for the first time, I usually make four checks before building any reports. They take only a few minutes and often catch unpleasant surprises like message 4 or the empty text in message 7.
First, I check the column type. The next queries will differ for text, json, and jsonb: some will require a cast, and with raw text, you also need to make sure every row can be cast successfully. You can see the type in the table schema or check it with pg_typeof(column).
Then I open two or three documents with jsonb_pretty. I usually choose one short document, one long one, and one from the middle of the period. A single row can make every document look as though it has the same structure; two or three often reveal different branches or an unexpected type.
After that, I count the top-level types:
SELECT jsonb_typeof(payload) AS kind, count(*) AS events
FROM app_events
GROUP BY jsonb_typeof(payload)
ORDER BY events DESC;
For app_events, the result contains one row: all 36 events are objects. That's a good result, but it's better to see the number 36 in the output than to assume it from the first two events. The raw stream is different: only three of its seven valid messages are objects.
Finally, I decide whether I'll ever need the original text. If a document comes from an external system and may later be involved in investigating a dispute or incident, I preserve the raw version alongside the jsonb, for example in a neighboring column.
Key takeaways
- consists of objects
{...}, arrays[...], and scalars: strings, numbers,trueandfalse, andnull. Objects and arrays can be nested inside one another to any depth. ::jsonbparses text as a document,jsonb_typeofreturns the value's type, andjsonb_prettyformats a long document into an indented layout.[],42,"hello", andnullare valid JSON. The top level doesn't have to be an object; JSONnulland SQLNULLare different things.jsonpreserves the original text, including whitespace and duplicate keys.jsonbstores the parsed tree: original whitespace disappears, PostgreSQL assigns its own key order, and only the last value survives when a key is duplicated.- Casting documents to
jsonbis convenient when you want to compare their content: key order no longer affects equality, while array element order and value type still do. ::jsonbdoesn't skip invalid text; it stops the entire query. So for now, we cast rows from the raw stream only when we already know their JSON is valid.
We've figured out how the parcels are structured. But the commandant needs the numbers inside them: the price shown when a product was viewed, which city the customer lives in, and what's inside an order. In the next lesson, we'll start extracting individual values. PostgreSQL has two very similar arrow operators for that—and they're surprisingly easy to mix up at first.
SELECT 'app_events' AS source_table, pg_typeof(payload)::text AS col_type, payload::text AS doc
FROM app_events
WHERE event_id = 1
UNION ALL
SELECT 'payments', pg_typeof(response)::text, response::text
FROM payments
WHERE payment_id = 2
UNION ALL
SELECT 'product_cards', pg_typeof(attrs)::text, attrs::text
FROM product_cards
WHERE product_id = 13
UNION ALL
SELECT 'user_settings', pg_typeof(settings)::text, settings::text
FROM user_settings
WHERE user_id = 23
UNION ALL
SELECT 'raw_inbox', pg_typeof(body)::text, body
FROM raw_inbox
WHERE msg_id = 3;