Extracting Clean Product Catalogs From Schema.org JSON-LD & OpenGraph With Python
Stop fixing broken CSS selectors every month. Parse embedded Schema.org JSON-LD blocks and Offer arrays directly with Python to extract clean pricing, stock, and GTIN catalogs.

Senior Data Specialist & Automation Architect

Every developer who builds price-monitoring or supplier catalog parsers hits the same annoying wall within sixty days.
You spend an afternoon carefully matching CSS classes like .price-box__amount-v2, only for the target platform to deploy a minor storefront redesign that renames half its layout classes overnight.
Suddenly your entire pipeline outputs empty strings or grabs "Related Items" prices by mistake.
On modern e-commerce storefronts, there is a vastly cleaner structured layer hiding in plain sight inside the document <head> or footer: Schema.org JSON-LD metadata.
Because brands depend on valid structured data to win Google Rich Snippets and sync Google Merchant Center inventory, these JSON payloads stay consistent even when visual layouts overhaul completely.
1. Why JSON-LD Beats CSS Selectors for Catalog Integrity
Unlike visual DOM elements designed around CSS Flexbox or Tailwind styling, Schema.org Product JSON-LD exposes standardized keys—sku, gtin13, priceCurrency, price, and strict enum strings like https://schema.org/InStock. You skip currency symbol regex hacks and currency decimal confusion immediately.
| Attribute | CSS DOM Selector Risk | JSON-LD Structured Advantage |
|---|---|---|
| Sale vs. List Price | Captures crossed-out price or promo installment splits | Explicit numeric offers.price + priceCurrency |
| Stock State | Requires fragile multilingual text matching | Normalized URI enum (InStock / OutOfStock) |
| Barcodes / MPN | Often hidden from visible buyer HTML | Standardized gtin12, gtin13, and mpn keys |
2. Handling Multiple Script Tags, Arrays & Nested @graph Objects
Real-world HTML rarely contains a single tidy Product JSON object.
SEO plugins such as Yoast, RankMath, or Shopify schema apps frequently wrap Organization, WebSite, BreadcrumbList, and Product inside a nested @graph array, or emit several independent <script type="application/ld+json"> blocks across the document.
Build your extractor defensively using Python's standard json module paired with BeautifulSoup 4 so nested objects flatten reliably without crashing on malformed trailing commas:
import json
from bs4 import BeautifulSoup
def extract_products_from_jsonld(html: str) -> list[dict]:
soup = BeautifulSoup(html, "html.parser")
candidates = []
for tag in soup.find_all("script", attrs={"type": "application/ld+json"}):
raw = tag.string or tag.get_text()
if not raw:
continue
try:
payload = json.loads(raw.strip())
except json.JSONDecodeError:
continue
items = payload if isinstance(payload, list) else [payload]
for node in items:
if isinstance(node, dict) and "@graph" in node:
candidates.extend(node["@graph"])
elif isinstance(node, dict):
candidates.append(node)
results = []
for item in candidates:
item_type = item.get("@type", "")
types = item_type if isinstance(item_type, list) else [item_type]
if "Product" not in types and "ProductGroup" not in types:
continue
results.append(item)
return results
3. Normalizing Single Offers, Offer Arrays & OpenGraph Fallbacks
Within extracted Product nodes, the offers property can arrive in three shapes depending on the storefront platform:
- Single Offer Dict: Simple single-SKU items emit one dictionary carrying direct
priceandavailabilitykeys. - Array of Variant Offers: Multi-size or multi-color items frequently emit a list of distinct Offer dictionaries, each carrying its child
sku,price, and individual stock flag. - AggregateOffer Wrapper: Some catalog listings output
lowPrice,highPrice, andofferCountinstead of explicit child SKUs—requiring a secondary variant JSON call if SKU granularity is needed.
Pair JSON-LD extraction with clean OpenGraph fallback extraction (og:title, og:image, product:price:amount) whenever an older template omits Schema markup on clearance or bundle URLs. Combining structured JSON-LD primary extraction with OpenGraph fallback lifts parse completeness across mixed catalogs close to 100%.
4. Validating Extracted Records Before Downstream Sync
Structured metadata still needs basic hygiene gates before entering pricing reports or staging spreadsheets. Check three common edge cases in Python after extracting records: decode HTML entities in name or description strings, and coerce prices through safe Decimal parsing.
Also normalize image fields consistently, since sites emit plain strings, URL lists, or ImageObject dictionaries.
Always respect crawl etiquette alongside clean parsing: check RFC 9309 robots.txt rules first, stick strictly to public unauthenticated pages, and cache HTML fixtures offline while tuning parser edge cases. Clean structured extraction saves hours of brittle selector maintenance across every storefront refresh.
5. Writing a Defensive Variant & Field Normalizer Function
Once candidate Product dictionaries are isolated from JSON-LD blocks, run every record through one deterministic normalization step before saving CSV or JSONL exports. Below is a compact Python helper covering price coercion, currency extraction, stock status flags, and nested image URLs cleanly:
from decimal import Decimal, InvalidOperation
def normalize_jsonld_product(node: dict, source_url: str) -> list[dict]:
title = str(node.get("name") or "").strip()
brand_raw = node.get("brand")
brand = brand_raw.get("name", "") if isinstance(brand_raw, dict) else str(brand_raw or "")
# Normalize image (string, list, or ImageObject dict)
raw_img = node.get("image")
if isinstance(raw_img, list) and raw_img:
raw_img = raw_img[0]
image_url = raw_img.get("url", "") if isinstance(raw_img, dict) else str(raw_img or "")
offers_raw = node.get("offers", [])
offers = offers_raw if isinstance(offers_raw, list) else [offers_raw]
rows = []
for offer in offers:
if not isinstance(offer, dict):
continue
raw_price = str(offer.get("price") or offer.get("lowPrice") or "").replace(",", "").strip()
try:
price = f"{Decimal(raw_price):.2f}" if raw_price else ""
except InvalidOperation:
price = ""
avail = str(offer.get("availability") or "")
in_stock = "InStock" in avail or "LimitedAvailability" in avail
rows.append({
"source_url": source_url,
"title": title,
"brand": brand.strip(),
"sku": str(offer.get("sku") or node.get("sku") or "").strip(),
"gtin": str(offer.get("gtin13") or offer.get("gtin12") or node.get("gtin13") or "").strip(),
"currency": str(offer.get("priceCurrency") or "USD").strip(),
"price": price,
"in_stock": in_stock,
"image_url": image_url.strip(),
})
return rows
6. Knowing When Public Storefront Endpoints Complement JSON-LD
Structured JSON-LD handles single-page attributes cleanly. Still, heavy apparel catalogs often keep full twenty-size stock grids outside the condensed head script.
In those cases, pair JSON-LD validation with lightweight public JSON API payload parsing or native Shopify product JSON descriptors where crawl policies permit.
- Combine Rather Than Duplicate: Capture canonical description, brand, and GTIN codes from Schema JSON-LD once, updating volatile price/availability deltas cleanly across scheduled syncs.
- Detect Schema Regressions Early: Log counts per run for empty SKU, missing currency, or failed JSON parse warnings so an unexpected plugin update triggers an instant alert instead of writing blank spreadsheets.
- Store Raw Fixture Snapshots for Unit Tests: Save five representative HTML files (simple item, out-of-stock item, multi-variant apparel, aggregate bundle, missing schema page) inside a local
tests/fixtures/directory so automatedpytestchecks validate parser edits in milliseconds.
7. Formatting Output Directly for Storefront Uploads & Margin Tracking
Clean JSON-LD extraction removes 90% of manual post-crawl spreadsheet repairs because brand names, GTIN strings, currency codes, and image links already arrive normalized.
Export output tables cleanly using UTF-8 BOM encoding (utf-8-sig) with explicit column types so client teams drop extracted catalogs directly into WooCommerce, Shopify Matrixify templates, or competitive price tracking sheets cleanly on the first pass.
Frequently Asked Questions
Common operational inquiries related to Extracting Clean Product Catalogs From Schema.org JSON-LD & OpenGraph With Python
Need a Resilient Scraper or Clean B2B Directory Dataset?
Skip brittle point-and-click exports. Book a complimentary 15-minute scoping call to evaluate target sources, compliance rules, and clean CSV/API delivery.

Written by Wp Hossain (Mikail Hossain)
Senior Data Extraction Specialist with 7+ years delivering Playwright crawlers, REST payload interceptors, and GDPR/robots-compliant public datasets (4.9/5 across 82 Fiverr reviews).