# JSON-LD 语法基础

URL: https://caijiao.org/json-ld/guide/syntax
Source: docs/json-ld/guide/syntax.md
Description: 讲解 JSON-LD 的核心语法，包括上下文、类型、标识符、值对象、语言标记、列表、图和嵌套实体的写法。

JSON-LD 保留 JSON 的基本结构，但引入一组以 `@` 开头的关键字。它们不是普通业务字段，而是告诉处理器如何解释数据。

## 基本骨架

```json
{
  "@context": "https://schema.org",
  "@type": "Person",
  "@id": "https://example.com/people/ada",
  "name": "Ada Chen",
  "jobTitle": "前端工程师"
}
```

| 字段 | 作用 |
| --- | --- |
| `@context` | 定义字段和类型来自哪里 |
| `@type` | 声明当前对象的类型 |
| `@id` | 声明当前实体的稳定标识 |
| `name` | 普通属性，由上下文映射到完整语义 |

## 对象类型

`@type` 可以是一个字符串，也可以是数组：

```json
{
  "@context": "https://schema.org",
  "@type": ["Person", "Author"],
  "name": "Ada Chen"
}
```

在 Schema.org 场景中，通常使用最贴近页面内容的一个类型即可。多类型更适合知识图谱或内部数据整合。

## 稳定标识符

`@id` 表示实体身份。多个文档中出现同一个 `@id`，可以被理解为同一个实体。

```json
{
  "@context": "https://schema.org",
  "@type": "Organization",
  "@id": "https://example.com/#organization",
  "name": "Example Docs",
  "url": "https://example.com"
}
```

常见做法：

- 页面主体：使用页面规范 URL。
- 站点组织：使用首页 URL 加片段，例如 `https://example.com/#organization`。
- 作者：使用作者主页 URL。
- 商品：使用商品详情页 URL 或稳定商品 URI。

## 嵌套实体

JSON-LD 可以直接嵌套对象：

```json
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "语义化数据指南",
  "author": {
    "@type": "Person",
    "@id": "https://example.com/authors/ada",
    "name": "Ada Chen"
  }
}
```

如果同一个实体在多处出现，优先给它稳定 `@id`，减少歧义。

## 数组

多个作者、图片或面包屑项都可以使用数组：

```json
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "多人协作文章",
  "author": [
    { "@type": "Person", "name": "Ada Chen" },
    { "@type": "Person", "name": "Lin Zhou" }
  ]
}
```

## 值对象

当普通字符串不够表达语言、数据类型或方向时，可以使用值对象：

```json
{
  "@context": "https://schema.org",
  "@type": "Book",
  "name": {
    "@value": "小王子",
    "@language": "zh-CN"
  }
}
```

## 图

`@graph` 用于在同一个文档中发布多个相互关联的实体：

```json
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "Organization",
      "@id": "https://example.com/#org",
      "name": "Example Docs"
    },
    {
      "@type": "WebSite",
      "@id": "https://example.com/#website",
      "publisher": { "@id": "https://example.com/#org" },
      "url": "https://example.com"
    }
  ]
}
```

`@graph` 很适合站点级实体、页面实体和组织实体同时出现的场景。

## JSON-LD 不是 JavaScript

`application/ld+json` 中必须是合法 JSON：

```json
{
  "ok": true,
  "count": 3,
  "items": ["a", "b"]
}
```

不要写成：

```js
{
  ok: true,
  count: 3,
  // JSON 中不能有注释
}
```

尾随逗号、单引号、未加引号的键名、注释和函数都会导致解析失败。
