Sub topic 8
Connecting Entities with @graph
This chapter assumes you can write JSON-LD with @context and @type, nest one entity inside another, and give an entity an @id. It shows how to describe several entities side by side and link them by reference, so each one is written once.
The problem with nesting alone
Nesting works well for a tree. An Article has one author, and the author is written inside the Article. A real page often describes a web of things instead:
- The Article is published by an Organization.
- The WebSite is published by the same Organization.
- The Organization owns the WebSite and appears again on other pages.
If you nest everything, the Organization's name, URL, and logo get copied into several places. The copies drift apart when someone edits one of them. They also leave a parser unable to tell whether two similar blocks describe one organization or two.
What @graph is
@graph is a JSON-LD keyword. Its value is an array of node objects. Each node is one entity, and the nodes sit next to each other instead of inside each other. You write @context once at the top, and it applies to every node in the array.
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "Organization",
"@id": "https://example.com/#organization",
"name": "Example Coffee Co.",
"url": "https://example.com/"
},
{
"@type": "WebSite",
"@id": "https://example.com/#website",
"url": "https://example.com/",
"publisher": { "@id": "https://example.com/#organization" }
},
{
"@type": "Article",
"@id": "https://example.com/cold-coffee#article",
"headline": "How to Brew Cold Coffee",
"isPartOf": { "@id": "https://example.com/#website" },
"publisher": { "@id": "https://example.com/#organization" }
}
]
}The Organization is defined once, and both the WebSite and the Article point to it. An object that contains only @id, such as { "@id": "https://example.com/#organization" }, is a node reference. It means "the entity with this identifier, described elsewhere in this graph."
How references are resolved
A JSON-LD processor merges all nodes that share an @id into one node. This gives you the following behavior:
- A node that appears in
@graphwith full details is the definition. - A node that contains only
@idis a reference to that definition. - If the same
@idappears with different properties in two places, the properties are combined into one entity. If the values conflict, the entity ends up with both values.
The identifier is a name, not a download link. https://example.com/#organization does not have to return anything when requested. The fragment (#organization) is a common convention because it gives you a unique name that cannot collide with a real page URL.
Choose identifiers that are:
- Stable. Do not generate a new one on every page build.
- Unique per entity. Two different things must never share an
@id. - Consistent across pages. Using
https://example.com/#organizationon every page tells consumers it is the same organization everywhere. - Written exactly the same each time. The match is a string comparison, so
httpandhttps, a trailing slash, and letter case all matter.
@graph compared with a top-level array
JSON-LD also allows a top-level array of objects, but each object then needs its own @context. The two forms compare like this:
| Form | `@context` | Best for |
|---|---|---|
| Top-level array | Repeated in each object | Independent entities that never link |
| Object with `@graph` | Written once | Entities that reference each other |
| Several `<script>` elements | Repeated in each element | Separate, unrelated blocks |
Keep one page's linked entities in a single @graph inside a single script element. A processor then sees all of them as one graph, and references between them are guaranteed to resolve. Consumers differ in how well they link nodes across separate script elements, so do not rely on it.
Reference or nested definition?
You can mix both styles. Use these rules to choose:
- Use nesting when an entity belongs to one parent and is not reused, such as the
Offerinside aProduct. - Use
@graphand references when two or more nodes point to the same entity, such as a shared Organization. - Use a full definition once. Put the details in one node. Every other mention should be a bare
@idreference.
A reference node should contain nothing but @id. If you add name to a reference "for convenience," you have created a second description that can drift away from the first.
Checking references automatically
References are plain strings, so a typo fails silently. The script below reports every reference that has no definition in the same graph. It is a small guard you can run in a build step.
import json
def find_dangling(document):
nodes = document.get("@graph", [])
defined = {node["@id"] for node in nodes if "@id" in node}
missing = set()
def walk(value):
if isinstance(value, dict):
if set(value) == {"@id"}:
if value["@id"] not in defined:
missing.add(value["@id"])
else:
for child in value.values():
walk(child)
elif isinstance(value, list):
for child in value:
walk(child)
for node in nodes:
for key, child in node.items():
if not key.startswith("@"):
walk(child)
return sorted(missing)
doc = json.loads("""
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "Organization",
"@id": "https://example.com/#organization",
"name": "Example Coffee Co."
},
{
"@type": "Article",
"@id": "https://example.com/cold-coffee#article",
"headline": "How to Brew Cold Coffee",
"publisher": { "@id": "https://example.com/#organisation" }
}
]
}
""")
print(find_dangling(doc))The script prints ['https://example.com/#organisation']. The spelling organisation in the reference does not match the defined organization, so the Article's publisher link is broken. A reference to a deliberately external entity, such as a Wikidata URL, will also be listed. Treat the output as a list of items to review, not as a list of failures.
Common mistakes with @graph
- Defining an entity twice with different details. Two Organization nodes with the same
@idmerge, and conflicting names produce two names. - Different
@idvalues for the same thing. If the homepage useshttps://example.com/#organizationand the article page useshttps://www.example.com/#org, consumers see two organizations. - Putting
@contextinside every node. It is harmless but redundant. Write it once at the top of the graph. - Using the page URL itself as an
@id. The page and the thing it describes are different entities, and a bare URL blurs them. Add a fragment such as#articleor#webpage. - Describing entities that are not on the page. Linking nodes does not make hidden content acceptable. Every entity in the graph should match what visitors can see.
- Making the graph larger than the page needs. More nodes mean more things to keep correct. Include an entity only if you will maintain it.
Exercise
A site has an Organization defined on every page. On the homepage its @id is https://example.com/#organization. On article pages, the Article's publisher is { "@id": "https://example.com/#org" }, and the Organization node in the same graph uses @id https://example.com/#organization. What is wrong, and how do you fix it?
Show answer
The reference #org does not match the defined #organization. Identifiers are compared as exact strings, so the Article points at an entity that has no details, and a consumer may treat it as a separate, empty organization. Change the reference to https://example.com/#organization, and use that same value on every page. A script like find_dangling would also have caught it.
Exercise
You are marking up a Product page. The Product has one Offer, and the Product's brand is the same Organization that publishes the WebSite. Which of these should be nested inside the Product, and which should be a separate node in @graph referenced by @id?
Show answer
Nest the Offer inside the Product. It belongs to that one product and is not reused. Make the Organization a separate node in @graph with its own @id, and reference it from the Product's brand and from the WebSite's publisher. It is shared by several nodes, so it should be defined once.