> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/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 解析器使用 Rust 编写，并通过了 100% 的[官方 JSON5 测试套件](https://github.com/json5/json5-tests)。[翻译后的测试套件](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={null}
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.`
* **Infinity 和 NaN**：正数和负数
* **显式加号**：`+42`

```ts theme={null}
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',
}`);
```

#### 错误处理

`Bun.JSON5.parse()` 在输入无效 JSON5 时抛出 `SyntaxError`：

```ts theme={null}
try {
  JSON5.parse("{invalid}");
} catch (error) {
  console.error("Failed to parse JSON5:", error.message);
}
```

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

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

```ts theme={null}
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={null}
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={null}
// 制表符缩进
JSON5.stringify(data, null, "\t");
```

#### 特殊值

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

```ts theme={null}
JSON5.stringify({ inf: Infinity, ninf: -Infinity, nan: NaN });
// {inf:Infinity,ninf:-Infinity,nan:NaN}
```

***

## 模块导入

### ES 模块

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

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

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

#### 默认导入

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import config from "./config.json5";

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

#### 命名导入

您可以将顶层属性解构为命名导入：

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { database, features } from "./config.json5";

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

### CommonJS

您也可以在 CommonJS 中 `require` JSON5 文件：

```ts app.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const config = require("./config.json5");
console.log(config.database.name); // "myapp"

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

***

## JSON5 热重载

当您使用 `bun --hot` 运行应用程序时，Bun 会在 JSON5 文件更改时重新加载它们：

```json5 config.json5 theme={null}
{
  server: {
    port: 3000,
    host: "localhost",
  },
  features: {
    debug: true,
    verbose: false,
  },
}
```

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
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={null}
bun --hot server.ts
```

***

## 打包器集成

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

```bash terminal icon="terminal" theme={null}
bun build app.ts --outdir=dist
```

在构建时解析意味着：

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

### 动态导入

JSON5 文件可以被动态导入：

```ts theme={null}
const { default: config } = await import("./config.json5");
```
