> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JSON5

> 通过运行时 API 和打包工具集成，使用 Bun 内置对 JSON5 文件的支持

在 Bun 中，JSON5 与 JSON、TOML 和 YAML 一样，是一等公民。你可以：

* 使用 `Bun.JSON5.parse` 和 `Bun.JSON5.stringify` 解析和序列化 JSON5
* 在运行时以模块形式 `import` 和 `require` JSON5 文件（支持热重载和监视模式）
* 通过 Bun 的打包工具在前端应用中 `import` 和 `require` JSON5 文件

***

## 兼容性

Bun 的 JSON5 解析器通过了官方 [JSON5 测试套件](https://github.com/json5/json5-tests) 100% 的测试。解析器使用 Zig 编写以实现最佳性能。你可以查看我们的 [翻译测试套件](https://github.com/oven-sh/bun/blob/main/test/js/bun/json5/json5-test-suite.test.ts) 查看每个测试用例。

***

## 运行时 API

### `Bun.JSON5.parse()`

将 JSON5 字符串解析为 JavaScript 值。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
import { JSON5 } from "bun";

const data = JSON5.parse(`{
  // JSON5 支持注释
  name: 'my-app',
  version: '1.0.0',
  debug: true,

  // 允许尾随逗号
  tags: ['web', 'api',],
}`);

console.log(data);
// {
//   name: "my-app",
//   version: "1.0.0",
//   debug: true,
//   tags: ["web", "api"]
// }
```

#### 支持的 JSON5 特性

JSON5 是基于 ECMAScript 5.1 语法的 JSON 超集。它支持：

* **注释**：单行注释 (`//`) 和多行注释 (`/* */`)
* **尾随逗号**：对象和数组中允许
* **未加引号的键**：有效的 ECMAScript 5.1 标识符可以用作键
* **单引号字符串**：除了双引号字符串外支持单引号
* **多行字符串**：使用反斜杠换行
* **十六进制数**：`0xFF`
* **数字前后的小数点**：`.5` 和 `5.`
* **无限大和 NaN**：正负无穷和非数字值
* **显式加号**：`+42`

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const data = JSON5.parse(`{
  // 未加引号的键
  unquoted: 'keys work',

  // 单引号和双引号
  single: 'single-quoted',
  double: "double-quoted",

  // 尾随逗号
  trailing: 'comma',

  // 特殊数字
  hex: 0xDEADbeef,
  half: .5,
  to: Infinity,
  nan: NaN,

  // 多行字符串
  multiline: 'line 1 \
line 2',
}`);
```

#### 错误处理

如果输入不是有效的 JSON5，`Bun.JSON5.parse()` 会抛出 `SyntaxError`：

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
try {
  JSON5.parse("{invalid}");
} catch (error) {
  console.error("解析 JSON5 失败:", error.message);
}
```

### `Bun.JSON5.stringify()`

将 JavaScript 值序列化为 JSON5 字符串。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
import { JSON5 } from "bun";

const str = JSON5.stringify({ name: "my-app", version: "1.0.0" });
console.log(str);
// {name:'my-app',version:'1.0.0'}
```

#### 美化输出

传入 `space` 参数来格式化输出并缩进：

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const pretty = JSON5.stringify(
  {
    name: "my-app",
    debug: true,
    tags: ["web", "api"],
  },
  null,
  2,
);

console.log(pretty);
// {
//   name: 'my-app',
//   debug: true,
//   tags: [
//     'web',
//     'api',
//   ],
// }
```

`space` 参数可为数字（空格数）或字符串（用作缩进字符）：

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
// 使用制表符缩进
JSON5.stringify(data, null, "\t");
```

#### 特殊值

与 `JSON.stringify` 不同，`JSON5.stringify` 会保留特殊数值：

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
JSON5.stringify({ inf: Infinity, ninf: -Infinity, nan: NaN });
// {inf:Infinity,ninf:-Infinity,nan:NaN}
```

***

## 模块导入

### ES 模块

可以直接将 JSON5 文件作为 ES 模块导入：

```json5 config.json5 theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  // 数据库配置
  database: {
    host: "localhost",
    port: 5432,
    name: "myapp",
  },

  features: {
    auth: true,
    rateLimit: true,
    analytics: false,
  },
}
```

#### 默认导入

```ts app.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import config from "./config.json5";

console.log(config.database.host); // "localhost"
console.log(config.features.auth); // true
```

#### 命名导入

可以将顶层属性作为命名导入进行解构：

```ts app.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { database, features } from "./config.json5";

console.log(database.host); // "localhost"
console.log(features.rateLimit); // true
```

### CommonJS

JSON5 文件同样可以在 CommonJS 中通过 require 引入：

```ts app.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
const config = require("./config.json5");
console.log(config.database.name); // "myapp"

// 解构也支持
const { database, features } = require("./config.json5");
```

***

## JSON5 热重载

当使用 `bun --hot` 运行你的应用时，JSON5 文件的变动会自动被检测并重载：

```json5 config.json5 theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  server: {
    port: 3000,
    host: "localhost",
  },
  features: {
    debug: true,
    verbose: false,
  },
}
```

```ts server.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { server, features } from "./config.json5";

Bun.serve({
  port: server.port,
  hostname: server.host,
  fetch(req) {
    if (features.verbose) {
      console.log(`${req.method} ${req.url}`);
    }
    return new Response("Hello World");
  },
});
```

使用热重载启动：

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun --hot server.ts
```

***

## 打包工具集成

当你导入 JSON5 文件并使用 Bun 打包时，JSON5 会在构建时被解析，并作为 JavaScript 模块包含：

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun build app.ts --outdir=dist
```

这意味着：

* 生产环境零运行时 JSON5 解析开销
* 更小的包体积
* 对未使用属性支持摇树优化（命名导入）

### 动态导入

JSON5 文件也支持动态导入：

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const { default: config } = await import("./config.json5");
```
