JSON-LD 进阶用法

基础 JSON-LD 可以只写 @context@type。当数据规模变大、实体之间关系变多,进阶能力会让结构更清晰、更容易复用。

使用 @graph 组织多个实体

一个页面往往同时包含页面实体、站点实体、组织实体和作者实体。用 @graph 可以把它们放在同一个文档里,并通过 @id 引用:

{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "Organization",
      "@id": "https://example.com/#organization",
      "name": "Example Docs",
      "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/articles/json-ld#article",
      "headline": "JSON-LD 进阶用法",
      "publisher": { "@id": "https://example.com/#organization" },
      "isPartOf": { "@id": "https://example.com/#website" }
    }
  ]
}

这样比在每个对象里重复组织信息更利于维护。

复用实体引用

如果一个作者出现在多篇文章中,不必每次都完整嵌套:

{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "Person",
      "@id": "https://example.com/authors/ada",
      "name": "Ada Chen"
    },
    {
      "@type": "Article",
      "headline": "语义化内容",
      "author": { "@id": "https://example.com/authors/ada" }
    }
  ]
}

消费方可以用相同 @id 合并实体信息。

语言映射

多语言数据可以使用语言映射:

{
  "@context": {
    "@vocab": "https://schema.org/",
    "name": {
      "@id": "name",
      "@container": "@language"
    }
  },
  "@type": "Product",
  "name": {
    "zh-CN": "旅行背包",
    "en": "Travel Backpack"
  }
}

如果只是单语言网站,直接使用字符串更简单。语言映射更适合国际化目录、开放数据和多语言知识库。

索引映射

索引映射可以让对象按业务键组织,同时仍然可展开为语义数据:

{
  "@context": {
    "@vocab": "https://schema.org/",
    "employees": {
      "@id": "employee",
      "@container": "@index"
    }
  },
  "@type": "Organization",
  "employees": {
    "engineering": {
      "@type": "Person",
      "name": "Ada Chen"
    },
    "design": {
      "@type": "Person",
      "name": "Lin Zhou"
    }
  }
}

这类结构在业务 API 中有价值,但面向搜索引擎的标记要优先遵循对应文档的示例和要求。

远程上下文治理

远程上下文会影响处理结果。生产系统应考虑:

  • 远程上下文是否稳定可访问。
  • 是否需要缓存上下文以避免请求失败。
  • 是否需要版本化上下文,例如 /context/v1.jsonld
  • 上下文变更是否会影响已有消费者。

API 设计中的 JSON-LD

如果要把 JSON-LD 用在 API 中,可以采用“普通业务 JSON + 上下文”的方式:

{
  "@context": {
    "@vocab": "https://schema.org/",
    "id": "@id",
    "type": "@type",
    "title": "headline",
    "publishedAt": "datePublished"
  },
  "id": "https://api.example.com/articles/1",
  "type": "Article",
  "title": "API 中的 JSON-LD",
  "publishedAt": "2026-09-22"
}

这样业务客户端仍然看到熟悉字段,语义客户端也能展开为标准结构。

何时保持简单

进阶能力不是越多越好。面向网页 SEO 时,优先选择:

  • Schema.org 文档和 Google 文档中的直观写法。
  • 稳定、可见、真实的页面数据。
  • 易测试、易生成、易维护的结构。

只有在确实需要实体复用、多语言、开放数据或知识图谱融合时,再引入复杂上下文和图结构。