← Back to blog

Turn Any Web Page Into Structured JSON: A Markdownify + JSON Schema Tutorial

Most web data still arrives as HTML built for humans. If you need a price, a job title, a publication date, or an author, you either write a CSS selector that breaks next Tuesday or you ask an LLM to read the whole page and hope it returns valid JSON.

Both approaches fail for the same reason: they skip the middle layer. HTML is markup for browsers, not a data format. Markdown is the compressed, structure-preserving representation of what a page actually says. And once you have clean markdown, "page → JSON" becomes a much smaller problem: fill a schema, validate it, retry on failure.

This tutorial builds that pipeline with two FetchAPI endpoints — Markdownify for body content and OGSnap for the page envelope — plus a JSON Schema and a validation loop. Every number in this post comes from real calls made against live pages, including the pages where extraction fails.

Why not just scrape with CSS selectors?

A selector like .price-tag encodes three assumptions at once: that the class exists, that it wraps exactly one value, and that the markup will stay that way. On a marketing site you don't control, all three assumptions expire. You end up maintaining a scraper per domain, and every redesign pages you at 2 a.m.

LLM-only extraction has a different failure: nondeterminism. Ask a model to "return the job details as JSON" and you get three different key names across three runs, dates in two formats, and occasionally a paragraph of prose where you expected null.

The schema-first pipeline fixes the second problem without reintroducing the first. Markdownify handles layout variance (it doesn't care whether the price sits in a <span> or a <div>, only that the text is there), and the schema pins the output shape.

Step 1: Extract the page as markdown

curl -s "https://fetchapi.tech/v1/markdownify?url=https://docs.python.org/3/library/json.html" \
  | python3 -m json.tool | head -12
{
  "content": "`json`\n\n— JSON encoder and decoder[¶](#module-json)\n\n**Source code:** [Lib/json/__init__.py]...",
  "title": "",
  "description": "",
  "url": "https://docs.python.org/3/library/json.html",
  "word_count": 3465,
  "char_count": 27879
}

Two fields matter more than the rest. word_count and char_count are your extraction health check — cheap integers you can gate on before you spend tokens. title is often empty, because not every page exposes a reliable headline to the extractor. Don't build your pipeline around it; get the title from OGSnap in the next step.

The content field is markdown with headings, lists, links, and tables preserved. That heading structure is what makes the next step work: a schema tells the model what to find, and headings tell it where to look.

Step 2: Get the page envelope with OGSnap

Metadata belongs in a separate call, because it comes from <meta> tags and JSON-LD rather than body text:

curl -s "https://fetchapi.tech/v1/ogsnap?url=https://www.python.org/" | python3 -m json.tool
{
  "url": "https://www.python.org/",
  "title": "Welcome to Python.org",
  "description": "The official home of the Python Programming Language",
  "image": "https://www.python.org/static/opengraph-icon-200x200.png",
  "site_name": "Python.org",
  "type": "website",
  "og": {
    "type": "website",
    "site_name": "Python.org",
    "title": "Welcome to Python.org",
    "description": "The official home of the Python Programming Language",
    "image": "https://www.python.org/static/opengraph-icon-200x200.png",
    "image:secure_url": "https://www.python.org/static/opengraph-icon-200x200.png",
    "url": "https://www.python.org/"
  },
  "twitter": {},
  "jsonld": [
    { "@context": "https://schema.org", "@type": "WebSite", "url": "https://www.python.org/" }
  ],
  "has_jsonld": true
}

jsonld is the underrated field. On news sites, docs platforms, and e-commerce pages it frequently carries datePublished, author, and Product/Offer data that the Open Graph tags omit. Here it's only a WebSite object with a search action — no article metadata — so treat its presence as a signal to look, not a guarantee of the fields you want.

Now you have two payloads: a verified envelope (title, description, canonical URL) and a body in markdown. Normalize the URL, drop tracking parameters, and hash the content so you can skip re-extraction later.

Step 3: Define the schema before you call the model

Pick a target you actually need. Job postings are a good test case: pages are mostly static, the fields are unambiguous, and the values are things you'd want to query.

{
  "type": "object",
  "additionalProperties": false,
  "required": ["job_title", "company", "location", "employment_type", "salary", "posted_date"],
  "properties": {
    "job_title":       { "type": "string" },
    "company":         { "type": "string" },
    "location":        { "type": ["string", "null"] },
    "remote":          { "type": ["boolean", "null"] },
    "employment_type": { "type": "string", "enum": ["full_time", "part_time", "contract", "internship", "unknown"] },
    "salary": {
      "type": ["object", "null"],
      "additionalProperties": false,
      "required": ["min", "max", "currency", "period"],
      "properties": {
        "min":      { "type": "number" },
        "max":      { "type": "number" },
        "currency": { "type": "string" },
        "period":   { "type": "string", "enum": ["year", "month", "day", "hour"] }
      }
    },
    "posted_date": { "type": ["string", "null"], "description": "ISO 8601 date, YYYY-MM-DD" }
  }
}

Three rules make this schema work in practice.

Use null for anything that might be absent. A schema that requires salary will make the model invent one. Every optional field should be explicitly nullable, and your prompt should say that null is the correct answer when the page is silent.

Constrain enums for categorical fields. employment_type has five legal values instead of infinite ones. Enums are the cheapest hallucination filter you get.

Put format instructions in description, not in the prompt. They travel with the field, survive refactors, and appear exactly where the model is deciding what to emit.

Step 4: Fill, validate, repair

Structured outputs get you close to valid JSON. They do not get you to semantically valid data — a model can return "salary": {"min": 90000, "max": 70000} and satisfy every type constraint. Validate, then repair:

import hashlib, json, os
import httpx
from pydantic import BaseModel, Field, ValidationError

API = "https://fetchapi.tech/v1"

def envelope(url: str) -> dict:
    r = httpx.get(f"{API}/markdownify", params={"url": url}, timeout=60)
    r.raise_for_status()
    data = r.json()
    md = httpx.get(f"{API}/ogsnap", params={"url": url}, timeout=30).json()
    return {
        "url": data["url"],
        "title": md.get("title") or "",
        "description": md.get("description") or "",
        "content": data["content"],
        "word_count": data["word_count"],
    }

class Salary(BaseModel):
    min: float
    max: float
    currency: str
    period: str

class JobPosting(BaseModel):
    job_title: str
    company: str
    location: str | None = None
    remote: bool | None = None
    employment_type: str = "unknown"
    salary: Salary | None = None
    posted_date: str | None = None

def extract(page: dict, client, schema: dict, attempts: int = 2):
    messages = [
        {"role": "system", "content":
         "Extract data from the page into the provided schema. "
         "Use null when a value is not stated. Never infer a salary, date, or location "
         "that is not written on the page. Quote numbers exactly as printed."},
        {"role": "user", "content":
         f"URL: {page['url']}\nTitle: {page['title']}\n\n{page['content'][:24000]}"},
    ]
    for i in range(attempts):
        resp = client.chat.completions.create(
            model="gpt-4o-mini",
            response_format={"type": "json_schema",
                             "json_schema": {"name": "job", "schema": schema, "strict": True}},
            messages=messages,
        )
        raw = resp.choices[0].message.content
        try:
            job = JobPosting.model_validate(json.loads(raw))
        except (ValidationError, json.JSONDecodeError) as e:
            messages += [
                {"role": "assistant", "content": raw},
                {"role": "user", "content": f"That output was invalid: {e}\nFix it. Return only JSON."},
            ]
            continue
        if job.salary and job.salary.min > job.salary.max:
            messages.append({"role": "user", "content":
                             "min is greater than max. Re-read the page and correct it."})
            continue
        return job, hashlib.sha256(raw.encode()).hexdigest()[:16]
    return None, None

The repair loop is the part people skip. Feeding the validation error back verbatim is usually enough, because the model has already read the page — it only needs to know which field it got wrong. The classic case is a printed range like "$90,000–$70,000": the model emits it in the order the page shows it, the range check rejects it, and one corrective turn fixes it without re-sending the whole document.

What extraction quality actually looks like

Here are four live pages, measured in one run: raw HTML bytes fetched directly, versus what Markdownify returned.

Page HTML Markdown chars Words Verdict
docs.python.org/3/library/json.html 116 KB 27,879 3,465 Clean
stripe.com/pricing 816 KB 4,547 671 Partial — tables missing
blog.cloudflare.com 196 KB 281 45 Failed — JS-rendered
news.ycombinator.com/item?id=1 6 KB 61 8 Failed — table layout

The docs page compresses 76% and loses nothing that matters. The Stripe pricing page compresses 99.4% — which sounds like a win until you notice the actual price table isn't in the output. The Cloudflare homepage returns 45 words because the posts render client-side. The Hacker News item returns a string of pipe characters because the comment tree is a <table>, not prose.

The lesson is a triage rule, not a tool complaint: word count is a signal, not a guarantee. Before you spend tokens on extraction, gate on word_count. Under ~150 words for a page that should have an article on it means the extractor got a shell. Log those URLs and route them elsewhere — a headless browser, a site-specific API, or manual review — instead of feeding 45 words of navigation chrome to a model and asking it for a salary.

Production notes

Cache on content hash, not URL. Prices change without the URL changing. Hash content and re-extract only when it differs; you get freshness and cost control from the same mechanism.

Truncate from the middle, not the end. Job requirements often live at the bottom of a long page, right after 2,000 words of company boilerplate. If you must cut, keep the first and last thirds and drop the middle.

Error contracts differ between endpoints. Markdownify failures come back as an HTTP 400 with a detail string. /v1/info returns HTTP 200 with an error key and has_transcript: false. If your client only checks status codes, you will silently ingest error strings as page content. Check the body.

Treat metadata as untrusted. OGSnap reads <meta> tags, and page authors control those. Never let a description field flow into a system prompt unfenced.

Wrap-up

The pipeline is four moves: extract markdown, resolve the envelope, constrain with a schema, validate and repair. Each step is a cheap GET or a single model call, and each one fails in a way you can detect — empty content, missing jsonld, a null where a number should be.

Try it on a page you already scrape:

curl -s "https://fetchapi.tech/v1/markdownify?url=YOUR_URL" | jq '{words: .word_count, chars: .char_count, title: .title}'
curl -s "https://fetchapi.tech/v1/ogsnap?url=YOUR_URL"    | jq '{title, description, has_jsonld}'

If the first call reports a plausible word count and the second returns a title, you have everything you need to fill a schema. The free tier requires no API key, so you can measure extraction quality across your own corpus before committing to a prompt design. Full parameter reference is in the docs.