Skip to main content
TutorialsNovember 23, 2026 · 14 min read

How to handle missing and null fields in scraped JSON

A null in scraped JSON can mean absent, unseen, invalid or invented. Build a schema, parser and tests that tell them apart.

How to handle missing and null fields in scraped JSON

Some of your scraped JSON has null in it, and your pipeline has to decide what to do. Dropping the row loses data. Filling in a default invents data. Both are wrong if you don't know why the field is empty.

This tutorial shows how to handle null fields in scraped JSON. You'll request nullable fields with Spidra's structured output, sort every field into one of four states with a small parser, and add tests that fail when anything invents a value. The code is Python and runs against three real product pages.

A null can mean four different things

JSON has two ways to say "nothing here": leave the key out, or send null. Scraped data adds two more problems: values in the wrong shape, and values the page never showed. Treat them as four separate states.

State

What you receive

What to do

absent

The key is missing

The result broke its contract. Reject the record.

null

The key is there and the value is null

The value is unknown. Keep it as unknown.

invalid

A value of the wrong type, like "£51.77" where a number belongs

Reject it or set it aside. Don't coerce it quietly.

inferred

A well-formed value the page text doesn't back

Treat it as unknown and log why.

A null doesn't prove the page lacks the information. JSON Schema makes the same point about absent keys, and the prompt vs schema post shows a job posting that doesn't mention remote work without forbidding it. Later in this tutorial, a page that displays three stars comes back with a null rating.

Ask for nullable fields in the schema

A schema fixes the field names and types, and every field in it comes back, with null when the page doesn't have the value. Mark a field nullable by adding "null" to its type, and use the description to say when null is the right answer.

Install the SDK with pip install spidra (Python 3.9 or later) and put your key in SPIDRA_API_KEY. This is the schema for a product page:

# parse_products.py
NULLABLE = lambda kind, hint: {"type": [kind, "null"], "description": hint}
SCHEMA = {
    "type": "object",
    "required": ["name", "price", "currency", "in_stock", "sku", "rating"],
    "properties": {
        "name": {"type": "string", "description": "The product name exactly as the page shows it"},
        "price": {"type": "number", "description": "The price as a plain number, without the currency symbol"},
        "currency": NULLABLE("string", "The currency symbol or code beside the price, or null if none is shown"),
        "in_stock": NULLABLE("boolean", "true or false only if the page says, otherwise null"),
        "sku": NULLABLE("string", "The SKU or product code, or null if the page shows none"),
        "rating": NULLABLE("integer", "The star rating from 1 to 5 if the page shows one, otherwise null"),
    },
}

name and price are plain types because every product page shows them. Write nullable fields as a type list, not anyOf: Spidra ignores anyOf and reports it in schema_warnings, and a Pydantic Optional produces one.

Here are the three pages. Bulbasaur shows a price, "45 in stock" and "SKU: 4391". The Dell laptop shows $1281.99 and "4 reviews", with no stock status and no SKU. The book shows £51.77, "In stock (22 available)" and a UPC. Send them in one batch with the schema:

import json, os
from spidra import Spidra

URLS = [
    "https://scrapeme.live/shop/Bulbasaur/",
    "https://webscraper.io/test-sites/e-commerce/allinone/product/40",
    "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",
]
client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
data = client.batch_scrape(URLS, prompt="Extract the product", schema=SCHEMA)
for item in data.items:
    print(json.dumps(item.result, ensure_ascii=False))

Output:

{"currency": "£", "in_stock": true, "name": "Bulbasaur", "price": 63, "rating": null, "sku": "4391"}
{"currency": "$", "in_stock": null, "name": "Dell XPS 13", "price": 1281.99, "rating": 4, "sku": null}
{"currency": "£", "in_stock": true, "name": "A Light in the Attic", "price": 51.77, "rating": null, "sku": "a897fe39b1053632"}

Three layouts, one shape. The Dell page shows no stock status or SKU, so both are null. The two rating values need a closer look, and you'll get to them after the usual cleanup.

The usual fixes turn unknowns into facts

Data-cleaning guides often reach for fillna. Here are the three results in a DataFrame (pip install pandas), then the usual cleanup:

# baseline.py
import pandas as pd

rows = [item.result for item in data.items]  # the three results above
df = pd.DataFrame(rows)
clean = df.fillna({"in_stock": False, "sku": "", "rating": 0})
print(clean[["name", "in_stock", "sku", "rating"]])

Output:

                   name in_stock               sku  rating
0             Bulbasaur     True              4391     0.0
1           Dell XPS 13    False                       4.0
2  A Light in the Attic     True  a897fe39b1053632     0.0

The Dell page never mentioned stock, so False is a claim the page didn't make, and any filter on in_stock now drops the laptop. The book now has a rating of 0, and you'll see next that its page shows three stars.

A null can hide a value the page shows, and a number can be one it doesn't

Spidra reads the text of a page, and the book page draws its stars with a CSS class instead of text. An evaluate browser action runs a script in the page and returns what it finds, so you can read the markup directly:

# star_check.py
from spidra import ScrapeParams, ScrapeUrl

BOOK = "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html"
SCRIPT = (
    "return JSON.stringify({star_class: document.querySelector('.product_main .star-rating').className, "
    "text_has_stars: /star/i.test(document.querySelector('.product_main').innerText)})"
)

page = ScrapeUrl(url=BOOK, actions=[{"type": "evaluate", "script": SCRIPT}])
result = client.scrape(ScrapeParams(urls=[page]))
print(result.data[0].action_results[0].result)

Output:

{"star_class":"star-rating Three","text_has_stars":false}

The page shows three stars and none of them is in its text, so the null means "not readable as text", not "no rating". You can read the class with an action like this one, or keep the rating unknown.

The Dell rating goes the other way. The request above returned rating: 4, and the page text says only "4 reviews". The relevant part of the page's markup holds a review count of 4 and three star icons:

<span itemprop="reviewCount">4</span> reviews
<span class="ws-icon ws-icon-star"></span> <span class="ws-icon ws-icon-star"></span> <span class="ws-icon ws-icon-star"></span>

So the 4 matches the review count, not a rating the page displays. A prompt-only request on the same page returned star_rating: null instead. A value being present doesn't make it right, and the answer can change with the request.

Sort every field into one of four states

The parser classifies each field into one of the four states and never gives it a default. Start with the state names and a small result type:

# fields.py
from dataclasses import dataclass
from typing import Any

VALUE, NULL, ABSENT, INVALID, INFERRED = "value", "null", "absent", "invalid", "inferred"


@dataclass(frozen=True)
class Read:
    state: str
    value: Any = None
    reason: str = ""

read() classifies one field. Its proof argument is a function that checks a value against the page text:

def read(obj, key, kind, text="", proof=None):
    if not isinstance(obj, dict) or key not in obj:
        return Read(ABSENT, reason="key missing")
    value = obj[key]
    if value is None:
        return Read(NULL)
    wrong_bool = isinstance(value, bool) != (kind is bool)
    if wrong_bool or not isinstance(value, kind):
        return Read(INVALID, reason=f"expected {getattr(kind, '__name__', 'number')}, got {value!r}")
    if proof and not proof(value, text):
        return Read(INFERRED, reason=f"{value!r} is not backed by the page text")
    return Read(VALUE, value)

The wrong_bool line matters because Python treats True as an int, so a boolean would otherwise pass as a price.

If you validate with Pydantic, Optional[str] = None gives you the same None for an absent key and a null. model_fields_set keeps the difference:

from typing import Optional
from pydantic import BaseModel

class Product(BaseModel):
    name: str
    isbn: Optional[str] = None

print(sorted(Product.model_validate({"name": "x"}).model_fields_set))
print(sorted(Product.model_validate({"name": "x", "isbn": None}).model_fields_set))

Output:

['name']
['isbn', 'name']

Pydantic also casts values by default, so "2.72" becomes a float unless you turn on strict mode. That is convenient in many places and risky for scraped prices.

Write the rejection and fallback rules down

Decide per field, in one place, what happens in each state. A required field that isn't a clean value rejects the record. An optional field that is null stays null, and one that is invalid or inferred becomes None with a reason. An absent key always rejects, because Spidra returns every schema field and a missing one means the result isn't what you asked for.

Each field gets a function that looks for its value in the page's markdown:

# rules.py
import re
from fields import ABSENT, VALUE, read

NUMBER = (int, float)

def shows(value, text):  return str(value) in text
def number(text, *forms): return any(re.search(rf"(?<![\d.]){re.escape(f)}(?!\d)", text) for f in forms)
def price(value, text):  return value > 0 and number(text, f"{value:.2f}", f"{value:g}")
def stock(value, text):  return bool(re.search(r"in stock|out of stock|sold out|available", text, re.I))
def rating(value, text): return bool(re.search(rf"\b{value} out of 5\b|\b{value}/5\b|\brated {value}\b", text, re.I))

The policy table then says what each field is and whether the record can live without it:

# field: (type, how to back it with the page text, record is rejected without it)
POLICY = {
    "name":     (str,    shows,  True),
    "price":    (NUMBER, price,  True),
    "currency": (str,    shows,  True),
    "in_stock": (bool,   stock,  False),
    "sku":      (str,    shows,  False),
    "rating":   (int,    rating, False),
}

build(raw, text) applies the policy and returns (record or None, states, reasons):

def build(raw, text):
    if not isinstance(raw, dict):
        return None, {}, [f"result is a {type(raw).__name__}, expected an object"]
    values, states, reasons, reject = {}, {}, [], False
    for key, (kind, proof, required) in POLICY.items():
        got = read(raw, key, kind, text, proof)
        states[key] = got.state
        values[key] = got.value if got.state == VALUE else None
        if got.reason:
            reasons.append(f"{key}: {got.reason}")
        reject = reject or got.state == ABSENT or (required and got.state != VALUE)
    return (None if reject else values), states, reasons

Two choices in the checks are worth copying. in_stock needs words like "in stock" or "available" on the page, and rating needs "4 out of 5", "4/5" or "rated 4", so "4 reviews" can't back it. Prices are matched with boundaries, because a plain substring test lets a price of 0 pass on the 0 in "i5-4210U".

If you do need a fallback, such as a currency taken from the site's configuration, fill it in a separate step that records where it came from, so an inferred value never looks like a read one. The consistent JSON post shows that pattern with a source-to-currency table.

Test that the parser refuses invented defaults

These tests pin the rules. Each one feeds the parser a value the page doesn't support and expects it to be refused. good() is a valid Dell record you override one field at a time, and DELL and BOOK are the pages' text:

# test_rules.py
import pytest
from rules import build

DELL = "#### $1281.99\n\n#### Dell XPS 13\n\n13.3\" Touch, Core i5-4210U\n\n4 reviews"
BOOK = "# A Light in the Attic\n\n£51.77\n\n In stock (22 available)\n\n| UPC | a897fe39b1053632 |"

def good(**changes):
    return {"name": "Dell XPS 13", "price": 1281.99, "currency": "$",
            "in_stock": None, "sku": None, "rating": None} | changes

def test_null_stays_null_and_is_never_a_default():
    record, states, _ = build(good(), DELL)
    assert states["in_stock"] == "null"
    assert record["in_stock"] is None and record["sku"] is None   # not False, not ""

def test_invented_stock_is_rejected_when_the_page_says_nothing():
    record, states, _ = build(good(in_stock=True), DELL)
    assert states["in_stock"] == "inferred" and record["in_stock"] is None

def test_a_review_count_is_not_a_rating():
    record, states, reasons = build(good(rating=4), DELL)
    assert states["rating"] == "inferred" and record["rating"] is None
    assert "rating" in reasons[0]

def test_stock_is_kept_when_the_page_backs_it():
    record, _, _ = build(good(name="A Light in the Attic", price=51.77, currency="£", in_stock=True), BOOK)
    assert record["in_stock"] is True

The rest cover invalid values, required fields, absent keys and the wrong shape:

def test_a_price_string_is_invalid_not_coerced():
    record, states, _ = build(good(price="1281.99"), DELL)
    assert record is None and states["price"] == "invalid"

def test_a_zero_price_is_not_accepted_as_a_default():
    record, states, _ = build(good(price=0), DELL)
    assert record is None and states["price"] == "inferred"

def test_a_boolean_is_not_a_price():
    record, states, _ = build(good(price=True), DELL)
    assert record is None and states["price"] == "invalid"

@pytest.mark.parametrize("field", ["name", "price", "currency"])
def test_a_null_required_field_rejects_the_record(field):
    record, states, _ = build(good(**{field: None}), DELL)
    assert record is None and states[field] == "null"

def test_a_missing_key_is_absent_and_rejects_the_record():
    raw = good(); del raw["sku"]
    record, states, _ = build(raw, DELL)
    assert record is None and states["sku"] == "absent"

def test_a_list_instead_of_an_object_is_rejected():
    record, _, reasons = build([good()], DELL)
    assert record is None and reasons == ["result is a list, expected an object"]

Run the suite with pytest -q:

............                                                             [100%]
12 passed in 0.02s

Run it on real pages

run() fetches the extraction and the same pages as markdown, then builds each record. A page that fails is kept with its error instead of disappearing, and failed pages aren't charged.

from urllib.parse import urlsplit
from rules import build

def run(client, urls=URLS):
    data = client.batch_scrape(urls, prompt="Extract the product", schema=SCHEMA)
    pages = client.batch_scrape(urls)  # the same pages as markdown, to check values against
    text = {page.url: page.result for page in pages.items if page.status == "completed"}
    accepted, rejected = [], []
    for item in data.items:
        if item.status != "completed":
            rejected.append((item.url, [item.error or item.status]))
            continue
        record, states, reasons = build(item.result, text.get(item.url, ""))
        odd = {key: state for key, state in states.items() if state != "value"}
        print(urlsplit(item.url).hostname.ljust(18), odd, *reasons)
        (accepted if record else rejected).append((item.url, record or reasons))
    return accepted, rejected


def main(client):
    accepted, rejected = run(client)
    print("accepted:", len(accepted), "rejected:", len(rejected))
    for _, record in accepted:
        print(json.dumps(record, ensure_ascii=False))


if __name__ == "__main__":
    main(Spidra(api_key=os.environ["SPIDRA_API_KEY"]))

Output:

scrapeme.live      {'rating': 'null'}
webscraper.io      {'in_stock': 'null', 'sku': 'null', 'rating': 'inferred'} rating: 4 is not backed by the page text
books.toscrape.com {'rating': 'null'}
accepted: 3 rejected: 0
{"name": "Bulbasaur", "price": 63, "currency": "£", "in_stock": true, "sku": "4391", "rating": null}
{"name": "Dell XPS 13", "price": 1281.99, "currency": "$", "in_stock": null, "sku": null, "rating": null}
{"name": "A Light in the Attic", "price": 51.77, "currency": "£", "in_stock": true, "sku": "a897fe39b1053632", "rating": null}

All three records are accepted. The Dell keeps in_stock and sku as unknown, and its inferred rating of 4 is replaced by None with the reason attached, instead of flowing into your database.

The schema is what makes this practical. Drop it and ask for the same fields in plain words, and the parser rejects every result:

pages = client.batch_scrape(URLS)
text = {page.url: page.result for page in pages.items}

loose = client.batch_scrape(URLS, prompt="Extract the product name, price, currency, whether it is in stock, SKU and star rating", output="json")
for item in loose.items:
    record, states, reasons = build(item.result, text[item.url])
    print(urlsplit(item.url).hostname.ljust(18), "rejected" if record is None else "accepted", reasons)

Output:

scrapeme.live      rejected ['name: key missing', "price: expected number, got '63.00'", 'rating: key missing']
webscraper.io      rejected ['result is a list, expected an object']
books.toscrape.com rejected ['name: key missing', "price: expected number, got '£51.77'", 'rating: key missing']

Without a schema the field is product_name instead of name, prices are strings, and one page comes back wrapped in a list. The prompt vs schema post covers when a prompt alone is enough.

What this approach doesn't catch

  • A text match is not proof. The Bulbasaur page lists related products, so a wrong price of £162 would still be found on the page and accepted. Add a range check or compare against a trusted source for fields that matter.
  • A null from a schema can still mean the value is in the markup, as the star rating showed. Read those fields with a browser action or leave them unknown.
  • On a Scrape result, ai_extraction_failed: true means the extraction step failed and content fell back to the page's markdown. It doesn't mean the data was missing.
  • Pages change. A field that was filled last month can be null after a redesign, so keep the states in your data and watch the share of nulls per field.

Conclusion

You now have a schema that asks for what a page may not show, a parser that sorts each field into value, null, absent, invalid or inferred, and tests that fail the moment a default sneaks in. Your ETL code no longer has to guess what an empty field means.

Spidra is what keeps the extraction side of this small:

  • One schema for every page. You describe the fields once and send the same schema with every URL in Scrape, so every result has the same fields, numbers as numbers, and null where the page has nothing. There's no parser to write per site and no selector to repair when a class name changes.
  • Fetching is handled. Real browsers, proxies and CAPTCHA solving are included, so you spend your time on rules instead of on getting the page. A page that still can't be read comes back as a failed item, not as bad data.
  • Batches that report their own failures. Send up to 50 URLs in one request, get a separate result for each, and see the error for any page that failed. Failed pages aren't charged.
  • A way to read what text can't show. On Scrape, browser actions such as evaluate read markup directly, which is how the star rating above can be recovered when you need it.
  • A path from script to schedule. Save the request as a preset, and a monitor can re-run it on a schedule and alert you when something changes.

Every plan has every feature, and the dashboard's Code button writes the request for whatever you fill in. Create a free account (300 credits, no card required), run parse_products.py on your own URL list, and add the fields your pipeline needs to POLICY.

Frequently asked questions

Ask for every field and use null for what's unknown. A schema request in Spidra returns every field in the schema, with null where the page has no value, so your code can read every key. Treat a missing key downstream as a broken result and reject it.

Share this article

You build the product.
Spidra handles the data work.

Start with 300 free credits, about 300 pages. No credit card required.