Test generated JSON-LD after it has been embedded in the actual HTML response. A valid JSON string can contain text that the HTML parser treats as the end of its enclosing script element. Checking json.loads before embedding will not expose that second interpretation.
This matters for legitimate CMS text. A tutorial may literally explain a closing script tag;an imported description may contain angle brackets. The publisher should preserve that text without truncating its data block or accidentally turning data into document markup.
The entity identity guide governs what the data means. This procedure governs how the same approved data survives serialization, HTML parsing and JSON decoding. It does not make user-submitted HTML safe to render elsewhere or certify a rich-result feature.
Keep the parser contexts separate
The HTML standard’s script-content restrictions describes the unusual parsing rules around script contents and dangerous literal sequences. Its JavaScript examples use escapes appropriate to JavaScript. JSON has its own escape grammar, so do not blindly copy a JavaScript-only escape into a JSON-LD string.
The fixture below replaces the less-than character with the JSON-compatible Unicode escape \u003c in the serialized representation. JSON decoding restores the original character. The purpose is to remove the HTML-significant literal from the surrounding raw-text context while preserving the data value.
Do not HTML-entity-encode the complete JSON string as though it were an attribute. Script text is a different context. Replacing quotation marks with entity text can leave JSON that no longer parses, and replacing content characters can change the value rather than preserve it.
Run the complete harmless round-trip fixture
This Python standard-library example contains only an educational text value. It creates no executable JavaScript and makes no network request. It checks a safe round-trip and requires the unprotected closing-tag case to fail after HTML extraction.
import json
from html.parser import HTMLParser
record = {
'@context': 'https://schema.org',
'@type': 'CreativeWork',
'name': 'Café: Literal HTML lesson',
'text': 'The literal </script> closes a script block.'
}
class Scripts(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=False)
self.inside = False
self.blocks = []
def handle_starttag(self, tag, attrs):
if tag == 'script':
self.inside = True
self.blocks.append('')
def handle_data(self, data):
if self.inside:
self.blocks[-1] += data
def handle_endtag(self, tag):
if tag == 'script':
self.inside = False
def extract(payload):
parser = Scripts()
parser.feed('<script type="application/ld+json">' + payload + '</script>')
assert len(parser.blocks) == 1
return parser.blocks[0]
raw = json.dumps(record, ensure_ascii=False)
safe = raw.replace('<', chr(92) + 'u003c')
assert json.loads(extract(safe)) == record
try:
json.loads(extract(raw))
except json.JSONDecodeError:
print('premature-end negative detected')
else:
raise AssertionError('Unsafe embedding unexpectedly passed')
print('safe round-trip PASS')
double = json.dumps(safe)
assert json.loads(extract(double)) != record
print('double-serialization negative detected')
The expected output has a detected premature-end negative, a passing safe round-trip, and a detected double-serialization negative. The expected record is the original object, not a second value reconstructed from the emitted JSON. That comparison catches a serializer that “fixes” the boundary by silently deleting meaningful text.
Preserve the HTML parser’s role
The small extractor is a bounded teaching fixture for this specific literal closing-tag case. It is not a complete browser conformance test or a replacement for the application’s real rendering pipeline. Run a browser check against the actual generated response before releasing the publisher change.
Inspect the JSON-LD script node’s textContent, parse that exact string as JSON and compare the material values with the approved record. Count relevant data blocks and inspect unexpected sibling elements. Searching the raw page for the expected name is insufficient if half the object sits outside the script node.
A browser view that looks normal also cannot establish the data survived. The visible article may remain readable while its structured-data object is truncated. Keep source HTML, parsed script text and decoded object as three distinct artifacts.
Add cases that distinguish corruption from faithful escaping
Extend the local record with a non-ASCII name, a quoted phrase, an ampersand and ordinary backslashes. Require the decoded values to match exactly. These inputs catch character loss and accidental double escaping without introducing any active script payload.
The displayed negative serializes the safe JSON text again as a JSON string. The extracted block still parses, but its decoded value is a string rather than the approved object. The equality assertion catches that change. Preserve the same expected object rather than redefining a string as acceptable merely because parsing succeeded.
Keep a malformed JSON case separately. A missing delimiter is a JSON syntax defect;a prematurely terminated HTML script is an embedding defect;a changed decoded value is data corruption. Reporting all three as invalid schema obscures the producer that needs repair.
Review the decoded value as a typed object
Require the decoded top-level value to have the expected object shape before checking individual fields. A valid JSON string containing the words CreativeWork can otherwise pass an overly broad text search while carrying no usable object at that level. The double-serialization negative makes this failure observable without any active payload.
Keep a separate approved reference for material values such as name and text. Do not calculate the expected object by parsing the emitted block under test. That circular comparison would accept the very encoding change the round-trip is supposed to detect. A release fixture needs an independent input record and an independently stated preservation rule.
Approve identity,syntax and embedding independently
The release record should identify the serializer revision, approved input object, emitted HTML, extracted script text, decoded result and the negative cases that failed as intended. Execute the actual displayed fixture when presenting it as runnable, and preserve its output separately from any production observation.
For the real publisher, check a representative ordinary record and the boundary-bearing record through the same build path. A unit helper can pass while another template still concatenates raw strings. Include all active producers in the scoped acceptance list.
Close when the approved values survive the real serialization and parsing path without extra document markup. Vocabulary validation, feature eligibility and search-engine selection remain separate checks. This is a precise publication-integrity result, not a promise that adding a safely embedded data block will earn a search feature.
