Sub topic 9
Structured Data That Mirrors the Visible Page
This chapter assumes you can read basic HTML and JSON, and that you have already written question-led headings and answer-first passages (earlier chapters). Structured data is the last layer on top of that work. It does not replace it.
What structured data is and what it does
Structured data is machine-readable markup that describes the content of a page. The most common format on the web is JSON-LD (JSON for Linked Data), a block of JSON placed in a <script type="application/ld+json"> element. The vocabulary usually comes from schema.org, a shared list of types such as Article, FAQPage, HowTo and Organization.
Structured data is a hint about what the page already says. It tells a parser: "this heading and paragraph are a question and its accepted answer." It does not make content more trustworthy, and it does not make a page more likely to be cited by itself. Search engines have used it for rich results for years. Whether a particular AI answer system reads it, and how much weight it gives it, varies by vendor and changes over time. Treat it as inexpensive reinforcement of a structure that must already be visible in the text.
The governing rule of this chapter:
Why mirroring matters
There are three reasons to keep markup and visible text identical.
- Search engine policies. Google's structured data guidelines say markup must represent content that is visible to users. Markup that describes hidden or misleading content can lose rich-result eligibility or trigger a manual action.
- Consistency across extraction paths. A system may read your visible text, your markup, or both. If they disagree, it has to pick one, and you do not control which.
- Maintenance. Two copies of an answer drift apart. The version in the markup is usually the one nobody remembers to update.
The relationship between page and markup
The arrows from A to C mean the markup is derived from the page, not written separately. In practice, the best way to guarantee agreement is to generate both from one source, such as one content file or one CMS field.
A worked example: FAQPage
Start with the visible HTML. The question is an h2, and the answer follows directly in a paragraph.
<section id="what-is-a-canonical-url">
<h2>What is a canonical URL?</h2>
<p>A canonical URL is the preferred address of a page when the same content is reachable at several URLs.</p>
</section>Now the JSON-LD that describes that same question and answer. Notice the strings are identical to the visible text.
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What is a canonical URL?",
"acceptedAnswer": {
"@type": "Answer",
"text": "A canonical URL is the preferred address of a page when the same content is reachable at several URLs."
}
}
]
}You place it in the page, usually in the <head> or at the end of the <body>:
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What is a canonical URL?",
"acceptedAnswer": {
"@type": "Answer",
"text": "A canonical URL is the preferred address of a page when the same content is reachable at several URLs."
}
}
]
}
</script>The text property may contain limited HTML, but plain text is simpler and avoids mismatches.
Choosing the right type
Pick the type that describes what the page really is. Do not pick a type because it has a rich-result feature you want.
| Page content | Suitable type | Mirror in visible text |
|---|---|---|
| A list of questions with answers written by the site | `FAQPage` | Each question and answer shown on the page |
| A step-by-step procedure | `HowTo` | The numbered steps shown in order |
| A blog post, guide or article | `Article` or `BlogPosting` | Headline, author, publication and modified dates |
| A page where users submit many answers to one question | `QAPage` | The question and the submitted answers |
| The publisher itself | `Organization` | Name and logo shown in the site header or footer |
Two cautions about this table. First, eligibility for rich results changes. Google has restricted FAQ and HowTo rich results in search for most sites, so check the current documentation before building a plan around them. The markup can still describe your page accurately, but do not expect a visual reward. Second, FAQPage is for content you author. Forum threads with user answers belong under QAPage.
Generating markup from one source
Hand-copying text into JSON invites drift. A short script that builds the JSON-LD from the same data used to render the page removes that risk. The example below is complete and runnable with Python 3.
import json
import html
faqs = [
{
"question": "What is a canonical URL?",
"answer": "A canonical URL is the preferred address of a page "
"when the same content is reachable at several URLs.",
},
{
"question": "Should every page have a canonical link?",
"answer": "Yes. Add a self-referencing canonical link to each page "
"so duplicates of it point to one preferred address.",
},
]
def render_html(items):
parts = []
for item in items:
parts.append(
"<section>\n"
f" <h2>{html.escape(item['question'])}</h2>\n"
f" <p>{html.escape(item['answer'])}</p>\n"
"</section>"
)
return "\n".join(parts)
def render_jsonld(items):
data = {
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": item["question"],
"acceptedAnswer": {"@type": "Answer", "text": item["answer"]},
}
for item in items
],
}
# Escape "</" so the text can never close the script element early.
payload = json.dumps(data, indent=2).replace("</", "<\\/")
return f'<script type="application/ld+json">\n{payload}\n</script>'
print(render_html(faqs))
print(render_jsonld(faqs))Because both functions read the faqs list, a change to one answer updates the page and the markup together. The replace("</", "<\\/") line matters: an answer containing </script> would otherwise end the script block and break the page.
Checking that markup and page agree
Even with generation, check the output. This script fetches nothing. It takes a saved HTML file, extracts the JSON-LD, and confirms that each question and answer string appears in the visible text.
import json
import re
import sys
from html.parser import HTMLParser
class Extractor(HTMLParser):
def __init__(self):
super().__init__()
self.in_ld = False
self.in_skip = False
self.ld_blocks = []
self.text = []
def handle_starttag(self, tag, attrs):
if tag == "script":
if dict(attrs).get("type") == "application/ld+json":
self.in_ld = True
self.ld_blocks.append("")
else:
self.in_skip = True
elif tag == "style":
self.in_skip = True
def handle_endtag(self, tag):
if tag == "script":
self.in_ld = False
self.in_skip = False
elif tag == "style":
self.in_skip = False
def handle_data(self, data):
if self.in_ld:
self.ld_blocks[-1] += data
elif not self.in_skip:
self.text.append(data)
def normalize(s):
return re.sub(r"\s+", " ", s).strip()
def main(path):
with open(path, encoding="utf-8") as f:
parser = Extractor()
parser.feed(f.read())
visible = normalize(" ".join(parser.text))
problems = 0
for block in parser.ld_blocks:
data = json.loads(block)
for q in data.get("mainEntity", []):
name = normalize(q["name"])
answer = normalize(q["acceptedAnswer"]["text"])
for label, value in (("question", name), ("answer", answer)):
if value not in visible:
problems += 1
print(f"MISSING {label}: {value[:70]}")
print("OK" if problems == 0 else f"{problems} mismatch(es)")
return problems
if __name__ == "__main__":
sys.exit(1 if main(sys.argv[1]) else 0)Run it as python check_jsonld.py page.html. It exits with code 1 when anything in the markup is absent from the visible text, so you can use it in a build or CI step. It handles only FAQPage blocks with a mainEntity list. Extend it if you use other types.
Common errors
- Markup for content that is not on the page. Adding an FAQ block to JSON-LD "for the crawlers" while the page has no FAQ is the clearest violation.
- Marking up content hidden behind tabs that never load. Content in a collapsed accordion is generally fine because users can open it. Content that is never rendered is not.
- Stale markup. You edit the paragraph and forget the JSON. Generate both from one source.
- Invalid JSON. A trailing comma or an unescaped quote makes the whole block unreadable. Validate it.
- Wrong type. Using
FAQPagefor a page with a single question and a marketing pitch, or for user-submitted answers. - Promotional answers. Answers that are mostly advertising may be ignored or penalized, with or without markup.
- Duplicate or conflicting blocks. A plugin and your template may each emit a
FAQPage. Look at the rendered page source, not only your template. - Treating markup as a citation lever. No vendor documents that adding JSON-LD earns citations. Do not spend time here before the writing and headings are right.
Validating the result
Use several checks, because each catches different faults.
- Run your own consistency script (above) on the built page.
- Paste the page URL or code into the Schema Markup Validator at validator.schema.org to confirm the JSON-LD is valid schema.org syntax.
- Use Google's Rich Results Test to see whether Google parses the markup and which features it recognizes.
- View the rendered source of the live page and confirm exactly one block per type you intend.
Where this fits
Semantic HTML (the previous chapter) already gives parsers section, list and table boundaries. JSON-LD adds an explicit label on top. If the HTML is a mess, the markup will not fix it. If the HTML is clean and the passages are self-contained, the markup is a small, low-risk extra.
Exercise
A page has an h2 "How long should I cache API responses?" with an answer paragraph. The developer adds a FAQPage JSON-LD block with three more questions that do not appear anywhere on the page, reasoning that crawlers will see them. What is wrong, and what are two ways to fix it?
Show answer
The markup describes content that is not visible to users, which breaks the mirroring rule and search engine guidelines, and it risks losing rich-result eligibility or a manual action. Fix it either by removing the three extra questions from the JSON-LD, or by writing those three questions and answers into the visible page (with matching text) and then keeping them in the markup. Generating both from one data source prevents the mismatch from recurring.
Exercise
Your answer text contains the string </script> inside a code sample, and you embed it in a JSON-LD answer. What breaks, and which line in the generator script prevents it?
Show answer
The browser's HTML parser ends the script element at the first </script>, so the JSON is cut off and invalid, and the rest of the text renders as page content. The line payload = json.dumps(data, indent=2).replace("</", "<\\/") escapes the sequence so it cannot close the element, while JSON parsers still read it as "</".
Exercise
You run check_jsonld.py and it prints "MISSING answer: A canonical URL is the preferred address...". The visible page does contain that sentence, but with a non-breaking space between two words in the HTML source. Why does the check fail, and how would you fix the script?
Show answer
Python's re \s matches Unicode whitespace for str patterns, so a non-breaking space is normally collapsed. Check first whether the page text is split by inline tags such as <strong> or <a>, because the script joins text nodes with a space, which can insert a space inside a word or before punctuation. Fix by comparing after also removing spaces around punctuation, or by joining text nodes with an empty string and normalizing both sides the same way. Also confirm the characters really are the same, since a typographic apostrophe in the page versus a straight one in the JSON would also fail.