Sub topic 13
Generating JSON-LD from application data
This chapter assumes you can write JSON-LD by hand, including nested entities and @id links. It also assumes you can embed a script element in HTML and read basic Python. Hand-written markup works for a few pages. Once your site has hundreds of products or articles, you need to generate it from the same data that renders the page.
Why generate instead of write
Hand-copied markup goes stale. A price changes in the database and the template updates, but a pasted JSON-LD block keeps the old value. Search engines then see a mismatch between the markup and the visible page. Generating both from one record removes that failure.
The approach has four rules:
- Build the markup from the same record that renders the visible content.
- Build a data structure first, then serialize it. Never assemble JSON by concatenating strings.
- Escape the output for the HTML context it lands in.
- Leave out properties you have no value for.
Build a dictionary, then serialize
In most languages, JSON-LD is a nested map of strings, numbers, lists, and other maps. Build that structure with your normal data types and let a JSON library write the text. The library handles quotes, backslashes, control characters, and Unicode correctly. A hand-built string breaks the first time a product name contains a double quote.
This is the minimal pattern:
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=False keeps characters such as é readable instead of writing \u00e9. Both forms are valid JSON, so this is a readability choice. The replace call is a safety measure, covered next.
Escape for the script element
JSON-LD sits inside a script element, and the HTML parser looks for </script before it knows anything about JSON. If a product name or review text contains </script><script>alert(1)</script>, the JSON string ends the element early and the rest runs as HTML. This is a cross-site scripting hole.
JSON permits \/ as an escape for /, so replacing </ with <\/ changes how the text is written but not what it means. A stricter option escapes every < as \u003c. This also covers the <!-- sequence, which can put a script element into a special parsing state:
import json
def to_script_element(data: dict) -> str:
payload = json.dumps(data, ensure_ascii=False)
payload = (
payload.replace("<", "\\u003c")
.replace(">", "\\u003e")
.replace("&", "\\u0026")
.replace("\u2028", "\\u2028")
.replace("\u2029", "\\u2029")
)
return '<script type="application/ld+json">' + payload + "</script>"
print(to_script_element({"name": "</script><script>alert(1)</script>"}))The output contains no raw <, so the element cannot be closed early. A JSON parser still reads the original string back unchanged.
If your framework has a built-in helper for embedding JSON in HTML, prefer it over a hand-rolled one. Check that it escapes <.
Map records to schema.org types
Write one small function per type. Each function takes your application's record and returns a dictionary. It is the only place that knows both your database column names and schema.org property names.
import json
from decimal import Decimal
IN_STOCK = "https://schema.org/InStock"
OUT_OF_STOCK = "https://schema.org/OutOfStock"
def product_jsonld(row: dict) -> dict:
offer = {
"@type": "Offer",
"price": f"{Decimal(row['price']):.2f}",
"priceCurrency": row["currency"],
"availability": IN_STOCK if row["stock"] > 0 else OUT_OF_STOCK,
"url": row["url"],
}
node = {
"@context": "https://schema.org",
"@type": "Product",
"name": row["name"],
"offers": offer,
}
if row.get("description"):
node["description"] = row["description"]
if row.get("image_url"):
node["image"] = row["image_url"]
return node
row = {
"name": 'Gooseneck Kettle, 1" spout',
"price": "39.9",
"currency": "EUR",
"stock": 12,
"url": "https://example.com/products/kettle",
"description": "",
"image_url": "https://example.com/images/kettle.jpg",
}
print(json.dumps(product_jsonld(row), indent=2))The function makes several decisions that are easy to get wrong:
- Price is a formatted string.
Decimalwith:.2favoids float artifacts such as39.900000000000006and always produces two decimal places. Use the currency's minor unit rules if you sell in currencies that differ. - Availability is derived. The stock count decides the URL, so the markup cannot say
InStockwhile the page says "sold out". - Empty values are omitted. An empty
descriptionis skipped. Emitting""ornullfor a property is worse than leaving it out, because validators may flag it and consumers may treat it as a real value. - The quote in the name needs no special handling.
json.dumpsescapes it.
Generate a breadcrumb from a path
Breadcrumbs are a good fit for generation because the structure is already in your routing or category tree. The position values come from list order, so you never number them by hand:
def breadcrumb_jsonld(trail: list[tuple[str, str | None]]) -> dict:
items = []
for index, (name, url) in enumerate(trail, start=1):
entry = {"@type": "ListItem", "position": index, "name": name}
if url:
entry["item"] = url
items.append(entry)
return {
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": items,
}
crumbs = breadcrumb_jsonld([
("Guides", "https://example.com/guides"),
("Cold Coffee", None),
])The last entry has no URL because it is the current page. Reorder or insert a level and the positions stay consistent.
Combine entities with a shared @graph
When one page needs an Organization, a WebSite, and an Article, build each node separately and then put them in one @graph. Define the Organization once in a function that returns a stable @id, and have every page generator reference it:
ORG_ID = "https://example.com/#organization"
def organization_node() -> dict:
return {
"@type": "Organization",
"@id": ORG_ID,
"name": "Example Coffee Co.",
"url": "https://example.com/",
}
def page_graph(*nodes: dict) -> dict:
return {"@context": "https://schema.org", "@graph": list(nodes)}Because @id values come from one constant, a rename changes every page at the next build. Keep each @id stable across deployments, and do not derive it from anything that changes, such as a timestamp.
Where to run the generator
| Approach | Strength | Risk |
|---|---|---|
| Server-side template | Markup is in the first HTML response; same data as the page | Needs a code change per type |
| Build step for static sites | No runtime cost; easy to review in version control | Stale until the next build |
| Client-side script | Works when you cannot edit server code | Depends on the crawler running JavaScript; can drift from content |
Prefer server-side or build-time generation. Client-side injection can work, but it adds a dependency on rendering that you cannot observe from your own logs.
Test the generator
Test the output as data, not as text:
- Call the mapping function with a representative record and assert on the dictionary.
- Serialize with your escape helper and parse the result with
json.loadsto confirm it round-trips. - Include a record with a quote, a
<, a non-ASCII name, a zero stock count, and a missing optional field. - Run a sample of generated pages through the Schema Markup Validator and the Rich Results Test in CI or as a periodic check.
Exercise
A product page's template inserts the product name into a hand-built string: '{"@type": "Product", "name": "' + name + '"}'. A product is named: Kettle "Pro" </script>. List two separate problems this causes and the fix for each.
Show answer
First, the double quotes around Pro end the JSON string early, so the output is invalid JSON; the fix is to build a dictionary and serialize it with a JSON library, which escapes quotes. Second, the </script> text closes the script element, so whatever follows is parsed as HTML (a cross-site scripting risk); the fix is to escape "<" as \u003c (or at least replace "</" with "<\/") after serialization. Both fixes keep the data unchanged when a JSON parser reads it back.