Usman Ishaq is a semantic SEO strategist and consultant, and the founder of Digital Vikingz. One rule he applies on his website is that schema states only what the page states. This post turns that rule into a script you can run before every deploy.
Why must structured data match the visible page?
Google's structured data guidelines say markup should describe content that users can see on the page. When the JSON-LD says a product costs 49 and the page shows 59, one of them is wrong, and a parser cannot tell which. Stale prices in templates, copied descriptions and hard-coded values are the usual causes.
Mismatches can also mean markup is ignored for rich results, so a quiet check is cheaper than finding out later.
What does the script compare?
It fetches a URL, extracts every JSON-LD block, flattens any @graph, and checks these fields against the visible text:
-
nameandheadlinemust appear as written. -
descriptionis checked by word overlap, since summaries are rarely identical. At least 80 percent of its words must appear on the page. -
pricemust match a number shown on the page. -
priceCurrencymust match a symbol or code shown on the page.
Visible text means everything in the HTML except <script>, <style>, <noscript> and <template> content.
The script
Install the dependencies with pip install requests beautifulsoup4 lxml, then save this as schema_check.py.
#!/usr/bin/env python3
"""Compare JSON-LD with visible page text: python schema_check.py URL"""
import json, re, sys
import requests
from bs4 import BeautifulSoup
CURRENCY = {"USD": ["$", "usd"], "GBP": ["£", "gbp"], "EUR": ["€", "eur"]}
NUMBER = re.compile(r"\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?")
def squash(text):
return re.sub(r"\s+", " ", str(text)).strip().lower()
def jsonld_nodes(soup):
nodes = []
for tag in soup.find_all("script", type="application/ld+json"):
try:
data = json.loads(tag.string or tag.get_text())
except json.JSONDecodeError as e:
print(f"WARN invalid JSON-LD block: {e}")
continue
stack = data if isinstance(data, list) else [data]
while stack:
item = stack.pop()
if not isinstance(item, dict):
continue
nodes.append(item)
graph = item.get("@graph")
if isinstance(graph, list):
stack.extend(graph)
return nodes
def offers(node):
found = node.get("offers")
found = found if isinstance(found, list) else [found]
return [o for o in found if isinstance(o, dict)]
def check(url):
html = requests.get(url, timeout=15, headers={"User-Agent": "schema-check/1.0"})
html.raise_for_status()
soup = BeautifulSoup(html.text, "lxml")
nodes = jsonld_nodes(soup)
for tag in soup(["script", "style", "noscript", "template"]):
tag.decompose()
page = squash(soup.get_text(" "))
words = set(re.findall(r"\w+", page))
numbers = {float(n.replace(",", "")) for n in NUMBER.findall(page)}
results = []
def record(node, field, ok, detail=""):
results.append((ok, node.get("@type", "?"), field, detail))
for node in nodes:
for field in ("name", "headline"):
value = node.get(field)
if isinstance(value, str):
record(node, field, squash(value) in page, value)
desc = node.get("description")
if isinstance(desc, str) and desc.strip():
tokens = re.findall(r"\w+", squash(desc))
share = sum(t in words for t in tokens) / len(tokens) if tokens else 1
record(node, "description", share >= 0.8, f"{share:.0%} of words found")
for offer in offers(node):
price = offer.get("price", offer.get("lowPrice"))
if price not in (None, ""):
try:
ok = float(str(price).replace(",", "")) in numbers
except ValueError:
ok = False
record(node, "price", ok, str(price))
code = offer.get("priceCurrency")
if code:
marks = CURRENCY.get(str(code).upper(), [str(code).lower()])
record(node, "priceCurrency", any(m in page for m in marks), str(code))
return nodes, results
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit(__doc__)
nodes, results = check(sys.argv[1])
print(f"JSON-LD nodes found: {len(nodes)}")
for ok, kind, field, detail in results:
print(f"{'PASS' if ok else 'FAIL'} {kind}.{field} {detail}")
failed = [r for r in results if not r[0]]
print(f"{len(results) - len(failed)} passed, {len(failed)} failed")
sys.exit(1 if failed else 0)
How do you use the result?
Run it with python schema_check.py https://example.com/product. The exit code is 1 when any check fails, so it works in CI after a staging deploy. A FAIL means look at the page, not that the markup is automatically wrong. Common explanations:
- The page shows the value in a different form, such as "forty-nine dollars" instead of 49.
- The value is injected by JavaScript, which
requestsdoes not run. - The markup is stale and the page is correct, which is the case worth catching.
Fix the source of truth, usually the template or CMS field, so schema and page read from the same value rather than being edited separately.
What are the limits?
The script does not validate schema types or eligibility for rich results. Use Google's Rich Results Test for that. It also checks only the fields listed above, so extend the loop for telephone, ratingValue or dates if your pages carry them.
If you want schema planned together with the pages it describes, see the website development service.
Usman Ishaq is a semantic SEO strategist and consultant, and the founder of Digital Vikingz. He plans websites around entities, attributes and values, then builds topical maps, briefs, pages, internal links and schema so businesses rank in Google and get named by ChatGPT, Gemini and Perplexity.
Top comments (0)