Sub topic 9
Placing JSON-LD in a Web Page
This chapter assumes you can write basic HTML, read JSON, and already know how @context and @type describe an entity. Here you will learn where JSON-LD goes in a page, how parsers find it, and which mistakes make it silently useless.
Why embedding matters
JSON-LD is a data format, not a page format. A browser ignores it, and a crawler has to find it inside a document that is mostly HTML. HTML defines one standard way to carry data blocks, the script element with a non-JavaScript type. JSON-LD uses the media type application/ld+json.
Because the browser does not recognize that type, it neither runs nor displays the contents. The block is inert text. Crawlers, validators, and your own scripts read it by looking for script elements with that exact type.
The basic form
This is the smallest useful embedding. It is the Article example from the plan, placed in a script element.
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "How to Brew Cold Coffee",
"datePublished": "2026-03-14T08:00:00+00:00",
"image": "https://example.com/images/cold-coffee.jpg",
"author": {
"@type": "Person",
"name": "Ana Torres",
"url": "https://example.com/authors/ana"
}
}
</script>Three details matter here.
- The
typeattribute must be exactlyapplication/ld+json. A value such astext/jsonorapplication/json-ldis not recognized. - The content must be one valid JSON document. Comments, trailing commas, and single-quoted strings are all syntax errors.
- The block contains JSON only. Do not add
<!-- -->comments or JavaScript assignments such asvar data = ...inside it.
Where to put the script
JSON-LD can sit in the head or in the body. Both locations are valid, and parsers treat them the same way.
| Location | Advantages | Drawbacks |
|---|---|---|
| `head` | Easy to find, kept apart from visible content, common in templates | Data may be far from the content it describes |
| `body` | Can sit next to the component it describes, convenient for component-based pages | Easy to lose when a component is removed or refactored |
Pick one convention for the site and apply it everywhere. The important rule is that the markup must exist in the HTML that the crawler receives. See the later sections on rendering for the consequences.
Multiple blocks on one page
A page may contain several JSON-LD script elements. Each is parsed as its own document.
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{
"@type": "ListItem",
"position": 1,
"name": "Guides",
"item": "https://example.com/guides"
},
{
"@type": "ListItem",
"position": 2,
"name": "Cold Coffee"
}
]
}
</script>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Organization",
"@id": "https://example.com/#organization",
"name": "Example Coffee Co.",
"url": "https://example.com/"
}
</script>Separate blocks are a good fit when different parts of a template produce different entities, such as a layout that emits the Organization and a page type that emits the Article. The cost is that each block is parsed on its own. Consumers that merge blocks into one graph can resolve an @id shared between them, but you should not rely on every tool doing so. When entities reference each other, a single @graph block is the safer choice, as covered in the previous chapter.
A top-level array is also legal JSON-LD. It holds several entities in one block, but each entity then needs its own @context. A @graph with a single @context is usually cleaner.
What the crawler sees
Search engines fetch your HTML, and many also render pages with JavaScript. JSON-LD can therefore arrive in two ways.
- It is in the server's HTML response.
- It is injected into the DOM by JavaScript after the page loads.
Both can work, but they differ in reliability.
Instead of relying on that, use the diagram below to follow the path from page to parsed data.
Markup placed in the initial HTML is found without any rendering step. Markup injected by JavaScript depends on the crawler rendering the page, which can be delayed and is not guaranteed for every consumer. Prefer server-rendered JSON-LD. If you must inject it with JavaScript, test the rendered result with a validator that renders the page.
Injecting JSON-LD with JavaScript
If your framework builds the page in the browser, you can add the block yourself. Create the element, set its type, and put the serialized data in textContent.
<script>
const data = {
"@context": "https://schema.org",
"@type": "Organization",
"name": "Example Coffee Co.",
"url": "https://example.com/"
};
const el = document.createElement("script");
el.type = "application/ld+json";
el.textContent = JSON.stringify(data);
document.head.appendChild(el);
</script>Use textContent, not innerHTML. With textContent the browser treats the string as plain text, so a value containing < cannot create elements.
Escaping and the early-close problem
The HTML parser looks for the end of a script element before any JSON parser sees the content. It stops at the first </script it finds, even if that text sits inside a JSON string. A value such as "</script><img src=x>" would close your block early and let the remaining text be parsed as HTML.
This is a correctness problem and also a security problem when the values come from users, such as product names or review text.
Many serializers escape <, >, and & as Unicode escapes such as \u003c. This is also valid JSON and avoids the problem entirely. The next chapters on generating markup show this in code.
You do not need to HTML-encode the content. Writing & inside a script block would put a literal & in your data, because script content is not decoded as HTML entities.
Common embedding mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Wrong `type` value | Block ignored | Use `application/ld+json` exactly |
| Trailing comma or comment | JSON parse error, block skipped | Run the text through a JSON parser |
| Smart quotes copied from a word processor | Parse error | Use straight `"` characters |
| `</script>` inside a string | Block ends early | Escape `<` as `<\/` or `\u003c` |
| Two `@context` keys in one object | Invalid or duplicate key behavior | Keep one `@context` per document |
| Markup injected only on user action | Never seen by crawlers | Render on page load or on the server |
| Markup describing content that is not on the page | May violate guidelines | Match the visible content |
A single syntax error invalidates the whole block, not just one property. Because blocks are parsed independently, an error in one block does not affect the others on the page.
Checking what you embedded
After placing the markup, confirm three things.
- The HTML source contains it. View the page source, not the browser's element inspector, to see what the server sent.
- It parses. Paste the block into any JSON validator, or load it in code.
- It means what you intended. A validator shows the entities it extracted, so you can compare them with the page.
Validators get a full chapter later. For now, a quick local check in Python can catch syntax errors before you publish.
import json
import re
import sys
import urllib.request
url = sys.argv[1]
with urllib.request.urlopen(url) as response:
html = response.read().decode("utf-8")
pattern = re.compile(
r'<script[^>]*type=["\']application/ld\+json["\'][^>]*>(.*?)</script>',
re.DOTALL | re.IGNORECASE,
)
blocks = pattern.findall(html)
print(f"Found {len(blocks)} JSON-LD block(s)")
for index, block in enumerate(blocks, start=1):
try:
data = json.loads(block)
except json.JSONDecodeError as error:
print(f"Block {index}: invalid JSON ({error})")
else:
kind = data.get("@type") if isinstance(data, dict) else "list"
print(f"Block {index}: valid, top-level type {kind}")Run it as python check_jsonld.py https://example.com/your-page. The regular expression is good enough for a quick check. It is not a full HTML parser, so a validator remains the authority.
Summary of rules
- Use a
scriptelement withtype="application/ld+json". - Put one valid JSON document in each block.
- Place blocks in the
headorbody, and be consistent. - Prefer markup in the server-rendered HTML.
- Escape
</inside values so user text cannot end the block. - Keep the markup consistent with the content visitors can see.
Exercise
A product page has a JSON-LD block that stops working after a developer adds a product named Kettle </script> Deluxe to the catalog. The JSON itself is valid. Explain why the markup breaks and give two ways to fix it.
Show answer
The HTML parser ends a script element at the first </script it sees, before any JSON parsing happens. The product name therefore closes the block early, which leaves truncated JSON and stray text parsed as HTML. Fix it by escaping </ as <\/ in the serialized JSON, or by escaping < as \u003c. Both produce the same string after JSON parsing. Do not HTML-encode the value, because script content is not decoded as entities.
Exercise
Your site builds pages in the browser, and a validator that only reads the raw server HTML finds no structured data, although the live page shows a JSON-LD block in the element inspector. What is the likely cause, and what change is the most reliable fix?
Show answer
The block is injected by JavaScript after load, so it is not in the HTML the server returns. Tools that do not render JavaScript never see it. The most reliable fix is to output the JSON-LD in the server-rendered HTML. If that is not possible, keep the injection running on page load and test with a validator that renders the page.