# @croct/json5-parser 中文文档

规范地址：https://npmcn.com/package/%40croct/json5-parser/

版本：0\.2\.2
npm 元数据更新时间：2025-12-01T13:55:11.313Z
中文译文更新时间：2026-11-11T01:07:17.154Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40croct/json5-parser
原文对照：https://npmcn.com/package/%40croct/json5-parser/?lang=original
项目主页：https://github.com/croct-tech/json5-parser-js
源码仓库：https://github.com/croct-tech/json5-parser-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：107 kB，44 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2025-02-28T23:33:16.591Z
- 最新版本发布：2025-12-01T13:55:11.083Z
- 近 30 天下载量：3843654（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：5（近 12 个月 1 个）

## 中文简介

用于维持缩进、间隔和注释的JSON5标注器和解析器.

## 安装

```sh
npm install @croct/json5-parser
```

也可以使用：`pnpm add @croct/json5-parser`、`yarn add @croct/json5-parser`、`bun add @croct/json5-parser`

## README

[![Croct](https://cdn.croct.io/brand/logo/repo-icon-green.svg)](https://croct.com/)  
**JSON5 解析器**  
用于维持缩进、间隔和注释的JSON5标注器和解析器.

[![Version](https://img.shields.io/npm/v/@croct/json5-parser)](https://www.npmjs.com/package/@croct/json5-parser) [![Build](https://github.com/croct-tech/json5-parser-js/actions/workflows/branch-validations.yaml/badge.svg)](https://github.com/croct-tech/json5-parser-js/actions/workflows/branch-validations.yaml) [![](https://api.codeclimate.com/v1/badges/e527bdbf3e2b58919c97/test_coverage)](https://codeclimate.com/repos/67c21d34cbf7e400df9b5dbc/test_coverage) [![](https://api.codeclimate.com/v1/badges/e527bdbf3e2b58919c97/maintainability)](https://codeclimate.com/repos/67c21d34cbf7e400df9b5dbc/maintainability)  
  
[\* 释放](https://github.com/croct-tech/json5-parser-js/releases) • 妇女 [QQ 报告错误](https://github.com/croct-tech/json5-parser-js/issues/new?labels=bug&template=bug-report.md) • 妇女 [请求特性](https://github.com/croct-tech/json5-parser-js/issues/new?labels=enhancement&template=feature-request.md)

## 概览

这个库提供了一个 API ,用于与 JSON 和 [杰森5号](https://json5.org/) 文档,同时保留其原始结构和格式. 与使用抽象语法树(AST)和丢弃格式的传统JSON解析器不同,这个库利用了混凝土语法树(CST)来保留每一个细节——注释,缩进和白空格.

理想编辑配置文件(例如, `package.json`, (中文(简体) ), `tsconfig.json`)或任何用户生成的JSON5内容,此库确保格式化在整个修改过程中保持不变.

### 主要特点

-   **保留格式化** – 在不丢失注释,缩进或间隔的情况下读取,修改,并写入JSON5文件.
-   **样式学习** – 将文档现有的格式样式自动应用于新条目.
-   **重新编排格式** – 自定义带有灵活选项的输出格式.
-   **类型安全** – Fully 为JSON5文档的工作输入了API.

## 安装

通过 [国家预防机制](https://www.npmjs.com/)数字 :

```sh
npm install @croct/json5-parser
```

## 使用量

库提供了一个简单的API,用于解析,操纵,并串行JSON5文档.

### 定 法

通常,你不需要直接与Lexer互动. 然而,您可以使用它来表示一个JSON5文档:

```ts
import {JsonLexer} from '@croct/json5-parser';

const tokens = JsonLexer.tokenize(
    `{
        // Comment
        "name": "John Doe",
        "age": 42,
    }`
);
```

### 分析

要分析 JSON5 文件 :

```ts
import {JsonParser} from '@croct/json5-parser';

const node = JsonParser.parse(
    `{
        // Comment
        "name": "John Doe",
        "age": 42,
    }`
);
```

可选地指定要缩小结果的根节点类型 :

```ts
import {JsonParser, JsonObjectNode} from '@croct/json5-parser';

const node = JsonParser.parse(
    `{
        // Comment
        "name": "John Doe",
        "age": 42,
    }`,
    JsonObjectNode
);
```

### 操纵

保留格式时修改值 :

```ts
// Get the value of a property
const name = node.get('name').toJSON();

// Update a property
node.set('age', 43);

console.log(node.toString());
```

新条目采用文档的现有样式 :

```ts
node.set('country', 'USA');

console.log(node.toString());
```

输出 :

```json5
{
    // Comment
    "name": "John Doe",
    "age": 43,
    "country": "USA",
}
```

格式化在块级应用,在同一文档中处理不同的样式:

```json5
{
  "name": "My Project",
  "version": "1.0.0",
  "keywords": ["json5", "parser"],
}
```

添加数组项时保留现有格式 :

```ts
node.set('stack', ['react', 'typescript']);
```

输出 :

```json5
{
  "name": "My Project",
  "version": "1.0.0",
  "keywords": ["json5", "parser"],
  "stack": ["react", "typescript"],
}
```

要重置格式并应用新样式:

```ts
node.reset();

console.log(node.toString({/* formatting options */}));
```

输出 :

```json5
{
  "name": "My Project",
  "version": "1.0.0",
  "keywords": [
    "json5",
    "parser"
  ],
  "stack": [
    "react",
    "typescript"
  ]
}
```

参见 [格式化](https://npmcn.com/package/%40croct/json5-parser/#readme-formatting) 关于现有选项的详情.

要在保存格式化的同时更新文档,请使用 `update` 方法 :

```ts

node.update({
    ...node.toJSON(),
    "version": "2.0.0",
});
```

这个 `update` 方法将新内容与现有文档相协调,保留注释、缩进和间隔.

对于单个更新,宁可 `set` 提高性能的方法:

```ts
node.set('version', '2.0.0');
```

要合并两个文档,同时保留这两个文档的评论和格式,请使用 `merge` 方法 :

```ts

const destinationCode = `{
  // Destination pre-foo comment
  "foo": "value",
  // Destination post-foo comment
  "baz": [1, 2, 3]
}
`;

const sourceCode = `{
  /* Source pre-bar comment */
  "bar": 123, /* Inline comment */
  /* Source post-bar comment */
  "baz": true /* Another inline comment */
}
`;

const source = JsonParser.parse(sourceCode, JsonObjectNode);
const destination = JsonParser.parse(destinationCode, JsonObjectNode);

destination.merge(source)

console.log(destination.toString());
```

输出 :

```json5
{
  // Destination pre-foo comment
  "foo": "value",
  /* Source pre-bar comment */
  "bar": 123, /* Inline comment */
  /* Source post-bar comment */
  "baz": true /* Another inline comment */
}
```

### 格式化

当你打电话 `toString(options)` 您可以控制输出格式化. 如果一个选项被省略,则格式从当前文档中学习并保持其样式。 如果无法推断出风格, 格式重回紧凑的样式,没有额外的空格或缩进.

#### 选项

| 选项 | 类型/价值 | 说明 |
| --- | --- | --- |
| `indentationLevel` | `number` | 文档的基缩进级. |
| `indentationCharacter` | `'space'|'tab'` | 缩进所用的字符 . |
| `lineEnding` | `'lf'|'crlf'` | 在文档中使用的新行序列 . |
| `string.quote` | `'single'|'double'` | 字符串值的引号样式. |
| `property.quote` | `'single'|'double'` | 属性密钥的引号样式 . |
| `property.unquoted` | `boolean` | 有效时允许未引用的属性密钥 . |
| `array.indentationSize` | `number` | 数组条目缩进大小 . |
| `array.trailingIndentation` | `boolean` | 在新线上收缩括号. |
| `array.leadingIndentation` | `boolean` | 缩进打开新线上的括号. |
| `array.entryIndentation` | `boolean` | 每个数组条目缩进 . |
| `array.trailingComma` | `boolean` | 在最后一个条目后添加一个后缀. |
| `array.commaSpacing` | `boolean` | 在数组中逗号后添加空格 . |
| `array.colonSpacing` | `boolean` | 在阵列中,在冒号后添加空格(对于内含的对象). |
| `object.indentationSize` | `number` | 对象属性缩进大小 . |
| `object.trailingIndentation` | `boolean` | 缩进关闭新线上. |
| `object.leadingIndentation` | `boolean` | 缩进打开新线上的保险套. |
| `object.entryIndentation` | `boolean` | 缩进每个对象属性. |
| `object.trailingComma` | `boolean` | 在最后一个属性后添加后缀逗号 . |
| `object.commaSpacing` | `boolean` | 在对象中逗号后添加空格. |
| `object.colonSpacing` | `boolean` | 在对象中以冒号后添加空格. |

#### 快速食谱

这里有一些常见的格式样式,通过结合不同的选项可以实现.

##### 1) 紧凑的单行数组; 漂亮的多行对象

```ts
node.toString({
    array: {
        leadingIndentation: false,   // keep arrays inline
        trailingIndentation: false,
        trailingComma: false,
        commaSpacing: true,
    },
    object: {
        entryIndentation: true,      // multi-line objects
        leadingIndentation: true,    
        trailingIndentation: true,
        indentationSize: 2,
        trailingComma: true,
        commaSpacing: true,
        colonSpacing: true,
    },
});
```

输出样式 :

```json5
{
  "name": "My Project",
  "keywords": ["json5", "parser"], // array kept inline
  "deps": {
    "typescript": "^5.6.0",       // multi-line object
    "vite": "^5.4.0",
  }
}
```

##### 2) 各地的标签,单引号,仅在必要时引用属性

```ts
node.toString({
  indentationCharacter: 'tab',
  string: {
      quote: 'single'
  },
  property: {
      quote: 'single', 
      unquoted: true
  },
  object: {
    leadingIndentation: true,
    entryIndentation: true,
    trailingIndentation: true,
    trailingComma: false,
    commaSpacing: true,
    colonSpacing: true,
  },
});
```

输出样式 :

```json5
{
    foo: 'bar',
    items: [
        'a',
        'b'
    ]
}
```

##### 3) 严格的紧凑样式( 逗号/ 冒号后没有空格)

```ts
node.toString();
```

输出样式 :

```json5
{"a":1,"b":[1,2,3]}
```

## 捐款

欢迎捐款!

-   报告问题 [问题跟踪器](https://github.com/croct-tech/json5-parser-js/issues)。 。 。 .
-   对于重大的变化, [打开一个问题](https://github.com/croct-tech/json5-parser-js/issues) 首先讨论.
-   确保测试覆盖面相应得到更新.

## 测试

安装依赖性 :

```sh
npm install
```

运行测试 :

```sh
npm run test
```

要检查样式问题的 Lint 代码 :

```sh
npm run lint
```

## 常见问题

### @croct/json5-parser 是什么？

用于维持缩进、间隔和注释的JSON5标注器和解析器\.

### 如何安装 @croct/json5-parser？

在项目目录运行 npm install @croct/json5-parser，或使用 pnpm add / yarn add / bun add。

### @croct/json5-parser 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @croct/json5-parser 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @croct/json5-parser 可以商用吗？

@croct/json5-parser 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @croct/json5-parser 的下载量有多少？

根据 npm 官方下载统计，@croct/json5-parser 在 2026/10/11 – 2026/11/09 这 30 天内被下载 3,843,654 次，日均约 128,122 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @croct/json5-parser 还在维护吗？

最新版本 0\.2\.2 发布于 2025/12/01（11 个月前）；至今共发布 5 个版本，其中过去 12 个月发布了 1 个；首次发布于 2025/03/01。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

