Sub topic 13
Generating JSON-LD from application data
This chapter assumes you can write JSON-LD by hand, know how to embed it in a <script> element, and can read basic Python. Hand-written markup works for a single page. For a catalog of products or a blog with hundreds of posts, you generate the markup from the same data that renders the page.
Why generate instead of hand-write
Generated markup reads from one source of truth. If the price changes in your database, the page and its JSON-LD change together. This avoids the most common maintenance error: markup that no longer matches the visible content.
Build a dictionary, then serialize it
Do not assemble JSON by concatenating strings. A product name containing a quote or a backslash would produce invalid JSON. Build a native data structure (a dictionary in Python) and let a serializer handle quoting and escaping.
import json
product = {
"@context": "https://schema.org",
"@type": "Product",
"name": "Pour-Over Kettle",
"offers": {
"@type": "Offer",
"price": "39.90",
"priceCurrency": "EUR",
},
}
payload = json.dumps(product, ensure_ascii=False).replace("</", "<\\/")
html = '<script type="application/ld+json">' + payload + '</script>'
print(html)Two details matter here:
ensure_ascii=Falsekeeps characters such as "é" readable instead of turning them into\u00e9escapes. Both forms are valid JSON..replace("</", "<\\/")protects the page. The HTML parser ends a script element at the first</script>it sees, even inside a JSON string. If a product description contained</script><script>alert(1)</script>, the data could inject code into your page. In JSON,\/is a legal escape for/, so parsers read the same value back, but the browser no longer sees a closing tag.
Keep value types correct
Application data often has the wrong type for schema.org. Convert it before serializing.
| Source value | Problem | Fix |
|---|---|---|
| Price stored as cents (`3990`) | Schema.org expects a decimal amount | Format as `"39.90"` |
| Python `datetime` | `json.dumps` cannot serialize it | Call `.isoformat()` |
| Missing optional field (`None`) | Produces `null`, which is noise | Omit the key |
| Internal status code | Not a schema.org value | Map to `https://schema.org/InStock` |
Reuse the same data as the page
Write one function that takes your record and returns the dictionary. Call it from the same code path that renders the visible page, so both use the same record.
def product_jsonld(record):
data = {
"@context": "https://schema.org",
"@type": "Product",
"name": record["name"],
"offers": {
"@type": "Offer",
"price": f"{record['price_cents'] / 100:.2f}",
"priceCurrency": record["currency"],
},
}
if record.get("image_url"):
data["image"] = record["image_url"]
return dataThe if leaves out image when no image exists. An empty string or null is worse than an absent property.
Check the output
Generating markup does not make it valid. Add a test that parses your output with json.loads and checks required properties. Also run a sample page through the validators from the earlier chapter.
Exercise
A product description contains the text </script>. Why is json.dumps alone not enough to embed it safely, and what fixes it?
Show answer
json.dumps does not escape /, so the browser's HTML parser sees </script> and ends the script element early, which can let the rest of the text run as page content. Replacing </ with <\/ in the serialized string fixes this. JSON parsers read \/ as /, so the data stays the same.
Exercise
Your database stores a price as the integer 1250 (cents) and a datetime for datePublished. How do you convert each before building the dictionary?
Show answer
Format the price as a decimal string such as "12.50" (for example, f"{1250 / 100:.2f}"). Convert the datetime with .isoformat() to get an ISO 8601 string.