Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท JSON

JSON-LD and Embedding JSON in HTML

Add JSON-LD structured data to a page, read it with JavaScript, and embed application data as a JSON data island without opening an XSS hole.

So far JSON has travelled over the network. It also lives inside HTML pages, in two common ways. The first is JSON-LD, a format that describes what a page is about (an article, a product, a recipe, an event) for search engines and other programs. The second is the data island: a block of JSON placed in the page by the server so that your script can start without making a request.

Both use the same tag, <script> with a type that browsers do not run, so the content is data rather than code. Both also have one serious pitfall: JSON text inside HTML must be written carefully, or a user's text can break out of the tag and run as script. This lesson shows how to write, read and generate both, and how to embed JSON safely.

JSON inside a page

JSON-LD Tells search engines what the page is.
Data island Starts the app with data, no request.
Escaping Stops text from closing the tag.
1 / 2

What JSON-LD is

JSON-LD (JSON for Linking Data) is a way to say what things mean. Its vocabulary usually comes from schema.org, a shared list of types (Article, Product, Recipe, Event, Person, BreadcrumbList) and their properties. Search engines read it to show rich results: star ratings, prices, cooking times, event dates, breadcrumb trails.

You place it in the page in a script tag with the type application/ld+json. It can go in the <head> or the <body>:

HTML
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "How fetch works",
  "datePublished": "2025-03-14",
  "author": { "@type": "Person", "name": "Ada Lovelace" }
}
</script>

Three special keys give JSON-LD its power:

  • @context says which vocabulary the keys come from. Usually "https://schema.org".
  • @type says what kind of thing this object is.
  • @id (optional) gives the thing an identifier, usually a URL, so that other objects can point to it.

Everything else is an ordinary JSON property. Values can be strings, numbers, nested objects (which have their own @type) and arrays. A page can contain several JSON-LD blocks, or one block with an array. Use the same facts as the visible page: structured data that disagrees with the content may be ignored by search engines.

You do not need to learn the whole linked-data theory. For most sites, the practical job is: choose the right schema.org type, fill in the properties the search engine documents for it, and test the page with a structured data testing tool.

Reading JSON-LD with JavaScript

JSON-LD is JSON, so a script can read it like any other data. Select the tags, take their text and parse it. This is how SEO audit tools and browser extensions work.

Find and parse the JSON-LD on a page

Notice that the page displays the same author and title as the JSON-LD says. Notice also the try/catch: one broken block (a trailing comma is enough) should not stop the others.

Generating JSON-LD

Most sites produce JSON-LD from data they already have. Build a JavaScript object and serialize it, rather than gluing strings together. Quotes, line breaks and Unicode in titles are then escaped for you:

JavaScript
function articleJsonLd(post) {
  return {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: post.title,
    datePublished: post.publishedAt.toISOString().slice(0, 10),
    author: { "@type": "Person", name: post.author },
  };
}

On the server (Laravel, Django, Express and so on) the same idea applies: build an array or dictionary, run it through the language's JSON encoder, and print the result inside the tag. A client-side script can also add JSON-LD after the page loads; search engines that run JavaScript will see it, but server-rendered markup is more reliable.

Data islands: starting an app without a request

A data island is JSON the server puts into the HTML so the script has its first data immediately. The typical use is a page that would otherwise load, then fetch its data, then render. Embedding the data skips the waiting.

HTML
<script type="application/json" id="initial-data">
{"user":{"id":7,"name":"Ada"},"cart":[{"sku":"A1","qty":2}]}
</script>
<script>
  const initial = JSON.parse(document.getElementById("initial-data").textContent);
</script>

The browser ignores a script whose type is not JavaScript, so nothing runs and the text stays untouched. This has two advantages over the older habit of writing <script>window.INITIAL = {...};</script>:

  1. It is data, so a strict Content Security Policy that blocks inline scripts does not block it (only the small reader script needs a nonce or a hash, or can live in a file).
  2. It forces you to treat the content as JSON, which is parsed with JSON.parse, never evaluated.

Keep islands small. They add to the HTML size on every page view and cannot be cached separately like an API response; for large or user-specific data, a normal request is better.

The danger: closing the tag

The HTML parser looks for the characters </script to find the end of a script element. It does this before any JSON is parsed, and it does not know about JSON strings. If a user's text contains </script><script>alert(1)</script>, and you print it inside your island, the island ends early and the rest runs as real script. This is a cross-site scripting (XSS) hole, even though your JSON was perfectly valid.

JSON.stringify alone does not protect you, because </script> is legal inside a JSON string. Two details also matter: <!-- can confuse the parser in older rules about script data, and the Unicode line separators U+2028 and U+2029 were once invalid in JavaScript string literals (now allowed, but harmless to escape).

The fix is to escape the dangerous characters as JSON Unicode escapes after serializing. < means < to the JSON parser, so the parsed data is unchanged, but the HTML parser never sees a <.

Escaping JSON for a script tag

The safe string shows </script> where the unsafe one shows </script>, yet after JSON.parse the data is identical to the original. That is the point: escaping is invisible to your program and decisive for the HTML parser.

Most server frameworks provide this already: Laravel's @json Blade directive and Js::from(), Django's json_script filter, Rails' json_escape and similar helpers. Prefer those over hand-written escaping, and never print json_encode($x) raw inside a script tag without the framework's escaping flags.

When to use which

You want to... Use
Help search engines understand a page JSON-LD with a schema.org type
Pass initial data to your script a application/json data island
Load data that changes, or is large or private an API request with fetch
Pass one small value a data-* attribute

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which script type marks a block of JSON-LD structured data?

    Search engines look for script tags with type application/ld+json.
  2. 2. Why does the browser not run a <script type="application/json"> block?

    Only recognised script types execute. Other types leave the text available through textContent.
  3. 3. Why is JSON.stringify(userData) not enough when printing JSON into a script tag?

    The HTML parser finds the end of the element before JSON is parsed. Escape < as \u003c so it never appears.
  4. 4. What does escaping < as \u003c do to the parsed data?

    The escape is a standard JSON string escape, so the parsed value is identical to the original.
  5. 5. Which pair of keys describes the vocabulary and the kind of thing in JSON-LD?

    @context names the vocabulary (such as https://schema.org) and @type names the thing's type.

Summary

  • JSON-LD describes a page with schema.org types in a <script type="application/ld+json"> block; use @context, @type, and make it match the visible content.
  • You can read it with JSON.parse(tag.textContent); generate it by serializing an object, never by gluing strings.
  • A data island (type="application/json") hands your script its first data without a request and is not blocked by an inline-script policy.
  • Always escape <, >, & and the line separators as \uXXXX when embedding JSON in HTML, or use your framework's helper.

Next: reading JSON on other back ends in Reading JSON in Python, Java and PHP.