DEV Community

Cover image for Audit the JSON-LD on your site with Python
Prox Digital Agency London
Prox Digital Agency London

Posted on

Audit the JSON-LD on your site with Python

JSON-LD, in this context, is the block of structured data inside a <script type="application/ld+json"> tag that tells search engines what a page describes: a product, an event, an organisation. Validators like the Rich Results Test check one URL at a time. That's fine during development, but it doesn't tell you what's happening across fifty templates six months after launch, when plugins have updated and content has changed.

This post builds a small Python script that fetches a list of URLs, extracts every JSON-LD block, and flags the problems that most often creep in after launch:

  • blocks that aren't valid JSON
  • types that appear more than once on a page when they shouldn't
  • entities missing the properties your templates are supposed to output
  • events whose dates have already passed

It isn't a replacement for Google's validators. It's a quick, repeatable inventory you can run on a schedule.

Why this is worth automating

Google's structured data guidelines are clear that markup has to stay accurate: "Provide up-to-date information. We won't show a rich result for time-sensitive content that is no longer relevant" (Google Search Central). The common failures are rarely dramatic. A theme update adds a second Organization block. A CMS field goes blank, so a property disappears. An event page stays live long after the event. None of these break the page, so nobody notices.

Setup

pip install requests
Enter fullscreen mode Exit fullscreen mode

Create urls.txt with one URL per line. Pick one or two examples of every template that outputs structured data: product, category, article, event, location, homepage.

The script

import json
import sys
from collections import Counter
from datetime import date
from html.parser import HTMLParser

import requests

HEADERS = {"User-Agent": "jsonld-audit/1.0"}

# Minimal "must have" properties per type. Extend for your own templates.
REQUIRED = {
    "Organization": ["name", "url"],
    "LocalBusiness": ["name", "address"],
    "Product": ["name", "offers"],
    "BreadcrumbList": ["itemListElement"],
    "Article": ["headline"],
    "BlogPosting": ["headline"],
    "Event": ["name", "startDate", "location"],
}

SINGLE_PER_PAGE = {"Organization", "BreadcrumbList", "Product", "WebPage"}


class JsonLdParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.blocks = []
        self._capture = False

    def handle_starttag(self, tag, attrs):
        if tag == "script" and dict(attrs).get("type") == "application/ld+json":
            self._capture = True
            self.blocks.append("")

    def handle_endtag(self, tag):
        if tag == "script":
            self._capture = False

    def handle_data(self, data):
        if self._capture:
            self.blocks[-1] += data


def entities(data):
    """Yield top-level entities, unpacking lists and @graph."""
    if isinstance(data, list):
        for item in data:
            yield from entities(item)
    elif isinstance(data, dict):
        if "@graph" in data:
            yield from entities(data["@graph"])
        elif "@type" in data:
            yield data


def types_of(entity):
    t = entity.get("@type", [])
    return t if isinstance(t, list) else [t]


def audit(url):
    problems, inventory = [], Counter()
    html = requests.get(url, headers=HEADERS, timeout=20).text
    parser = JsonLdParser()
    parser.feed(html)

    if not parser.blocks:
        return ["no JSON-LD found"], inventory

    for i, block in enumerate(parser.blocks, 1):
        try:
            data = json.loads(block)
        except json.JSONDecodeError as e:
            problems.append(f"block {i}: invalid JSON ({e.msg})")
            continue

        for entity in entities(data):
            for t in types_of(entity):
                inventory[t] += 1
                for prop in REQUIRED.get(t, []):
                    if prop not in entity:
                        problems.append(f"{t}: missing '{prop}'")

            end = entity.get("endDate") or entity.get("startDate")
            if "Event" in types_of(entity) and end and str(end)[:10] < date.today().isoformat():
                problems.append(f"Event '{entity.get('name')}' is in the past")

    for t, n in inventory.items():
        if t in SINGLE_PER_PAGE and n > 1:
            problems.append(f"{t} appears {n} times")

    return problems, inventory


def main(urls):
    failures = 0
    for url in urls:
        problems, inventory = audit(url)
        types = ", ".join(f"{t}x{n}" if n > 1 else t for t, n in sorted(inventory.items()))
        print(f"\n{url}\n  types: {types or '-'}")
        for p in problems:
            print(f"  ! {p}")
        failures += bool(problems)

    print(f"\n{len(urls) - failures}/{len(urls)} pages without problems")
    sys.exit(1 if failures else 0)


if __name__ == "__main__":
    main([line.strip() for line in open(sys.argv[1]) if line.strip()])
Enter fullscreen mode Exit fullscreen mode

How it works

JsonLdParser uses the standard library's HTMLParser to collect the text inside every application/ld+json script tag. No regular expressions over HTML, and no extra dependencies.

entities flattens the shapes JSON-LD commonly takes. Some sites output a single object, some a list of objects, and many SEO plugins output one object with an @graph array. The function walks all three and yields the top-level entities.

types_of handles @type being either a string or a list, which is valid JSON-LD and easy to forget.

audit parses each block separately, so one broken block doesn't hide the others. It counts types, checks your required properties, flags past events, and finally reports types that appear more than once when your site should only output one.

Running it

python audit_jsonld.py urls.txt
Enter fullscreen mode Exit fullscreen mode

Output looks like this (from a test page built to fail):

https://fake.example/
  types: Event, Organizationx2, Product
  ! Organization: missing 'url'
  ! Product: missing 'offers'
  ! Event 'Spring workshop' is in the past
  ! block 4: invalid JSON (Expecting property name enclosed in double quotes)
  ! Organization appears 2 times
Enter fullscreen mode Exit fullscreen mode

Each line points at something specific to check. The duplicate Organization often means a theme and an SEO plugin are both outputting it, with slightly different values.

The exit code is 1 if any page has problems, so the script fits into a scheduled CI job without any extra wiring.

Reading the inventory

The types line is often more useful than the problem list. It shows what each template is actually telling search engines, and it regularly surprises people. Common discoveries:

  • Types nobody asked for. SEO plugins and themes add markup automatically. You may find FAQPage, HowTo or Review types that no one on the team chose. Decide whether each one should be there.
  • Missing types. A product template with no Product in the inventory, or an article template with no Article, usually means a template change dropped the markup.
  • Different answers on the same template. If two product pages show different type lists, the data behind one of them is probably incomplete.

Save the inventory from each run. Comparing it before and after a release is the quickest way to see what a deployment changed.

Scheduling it

A weekly run is enough for most sites, plus a run after each deploy. In GitHub Actions, a scheduled workflow with a cron trigger, a Python setup step, pip install requests and python audit_jsonld.py urls.txt is all it takes. Because the script exits with 1 on problems, the job fails visibly and the usual notifications do the rest.

If your team doesn't use CI, a scheduled task on any machine that can reach the site works just as well. Send the output somewhere people will actually read it.

Customising the rules

The REQUIRED dictionary is deliberately small. It isn't Google's list of required properties for each rich result. It's your list of what your templates promise to output. If your product template should always include brand and sku, add them. If your articles should always name an author, add author to Article.

That distinction matters. Google's documentation for each feature lists its own required and recommended properties, and the Rich Results Test is the right tool for checking those. This script checks consistency with your own standards across many pages at once.

SINGLE_PER_PAGE works the same way. Some sites legitimately output several Product entities on a listing page; remove Product from the set if that's you.

Things to watch out for

  • JavaScript-injected markup. The script reads the HTML response. If your structured data is added by client-side JavaScript, it won't see it. That's also worth checking with URL Inspection in Search Console, since it shows the HTML Google rendered.
  • Visible content. Valid markup isn't the same as accurate markup. Google's guidelines say "Don't mark up content that is not visible to readers of the page". This script can't compare the markup to the page; a human spot-check still matters.
  • Time zones and partial dates. The past-event check compares the first ten characters of the date. It's good enough for flagging, not for edge cases around midnight.
  • Rate. Keep the URL list to representative pages. This is a template audit, not a crawl.

Extending it

Useful additions, depending on your site:

  • Compare a Product's offers.price with the price shown on the page, using a CSS selector for your template.
  • Flag Offer entities whose priceValidUntil has passed.
  • Save the inventory as JSON after each run and diff it against the previous run, so you see when a release adds or removes types.
  • Post the summary to Slack or Teams when the exit code is non-zero.

Where this fits

Auditing tells you when structured data has gone wrong. Choosing the right types and writing good markup in the first place is the bigger job, and this is a good companion read for it: a practical guide to schema markup with JSON-LD examples.

Put one URL per template in urls.txt, run the script weekly, and you'll catch the next duplicate plugin or stale event long before anyone else does.

Top comments (0)