@croct/json5-parser

中文文档
0.2.2发布于 2025/12/01MITTypeScriptCommonJS近 30 天下载 384.4万

A lossless JSON5 tokenizer and parser for Node.js that maintains indentation, spacing, and comments.

原始使用文档
文档目录10 节
  1. Overview
  2. Key features
  3. Installation
  4. Usage
  5. Lexing
  6. Parsing
  7. Manipulation
  8. Formatting
  9. Contributing
  10. Testing

Croct
JSON5 Parser
A lossless JSON5 tokenizer and parser for Node.js that maintains indentation, spacing, and comments.

Version Build

📦 Releases · 🐞 Report Bug · ✨ Request Feature

Overview

This library provides an API for working with JSON and JSON5 documents while preserving their original structure and formatting. Unlike traditional JSON parsers that use an Abstract Syntax Tree (AST) and discard formatting, this library leverages a Concrete Syntax Tree (CST) to retain every detail—comments, indentation, and whitespace.

Ideal for editing configuration files (e.g., package.json, tsconfig.json) or any user-generated JSON5 content, this library ensures that formatting remains intact throughout modifications.

Key features

  • Preserve formatting – Read, modify, and write JSON5 files without losing comments, indentation, or spacing.
  • Style learning – Automatically applies the document's existing formatting style to new entries.
  • Reformatting – Customize output formatting with flexible options.
  • Type safety – Fully typed API for working with JSON5 documents.

Installation

Install via NPM:

npm install @croct/json5-parser

Usage

The library provides a simple API for parsing, manipulating, and serializing JSON5 documents.

Lexing

Usually, you don't need to interact with the lexer directly. However, you can use it to tokenize a JSON5 document:

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

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

Parsing

To parse a JSON5 document:

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

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

Optionally, specify the expected root node type to narrow down the result:

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

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

Manipulation

Modify values while preserving formatting:

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

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

console.log(node.toString());

New entries adopt the document's existing style:

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

console.log(node.toString());

Output:

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

Formatting is applied at a block level, handling different styles within the same document:

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

Adding an array entry keeps the existing format:

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

Output:

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

To reset formatting and apply a new style:

node.reset();

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

Output:

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

Refer to the Formatting section for details on available options.

To update the document while preserving formatting, use the update method:


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

The update method reconciles the new content with the existing document, preserving comments, indentation, and spacing.

For single updates, prefer the set method for better performance:

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

To merge two documents while preserving comments and formatting from both, use the merge method:


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());

Output:

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

Formatting

When you call toString(options) you can control how the output is formatted. If an option is omitted, the formatter learns from the current document and keeps its style. If no style can be inferred, the formatter falls back to a compact style with no extra spaces or indentation.

Options

OptionType/ValuesDescription
indentationLevelnumberBase indentation level for the document.
indentationCharacter'space'|'tab'Character used for indentation.
lineEnding'lf'|'crlf'Newline sequence to use in the document.
string.quote'single'|'double'Quotation style for string values.
property.quote'single'|'double'Quotation style for property keys.
property.unquotedbooleanAllow unquoted property keys when valid.
array.indentationSizenumberIndentation size for array entries.
array.trailingIndentationbooleanIndent closing bracket on a new line.
array.leadingIndentationbooleanIndent opening bracket on a new line.
array.entryIndentationbooleanIndent each array entry.
array.trailingCommabooleanAppend a trailing comma after the last entry.
array.commaSpacingbooleanAdd space after commas in arrays.
array.colonSpacingbooleanAdd space after colons in arrays (for objects inline).
object.indentationSizenumberIndentation size for object properties.
object.trailingIndentationbooleanIndent closing brace on a new line.
object.leadingIndentationbooleanIndent opening brace on a new line.
object.entryIndentationbooleanIndent each object property.
object.trailingCommabooleanAppend a trailing comma after the last property.
object.commaSpacingbooleanAdd space after commas in objects.
object.colonSpacingbooleanAdd space after colons in objects.

Quick recipes

Here are some common formatting styles you can achieve by combining different options.

1) Compact, single-line arrays; pretty multi-line objects
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,
    },
});

Output style:

{
  "name": "My Project",
  "keywords": ["json5", "parser"], // array kept inline
  "deps": {
    "typescript": "^5.6.0",       // multi-line object
    "vite": "^5.4.0",
  }
}
2) Tabs everywhere, single quotes, properties quoted only when necessary
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,
  },
});

Output style:

{
    foo: 'bar',
    items: [
        'a',
        'b'
    ]
}
3) Strict compact style (no spaces after commas/colons)
node.toString();

Output style:

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

Contributing

Contributions are welcome!

  • Report issues on the issue tracker.
  • For major changes, open an issue first to discuss.
  • Ensure test coverage is updated accordingly.

Testing

Install dependencies:

npm install

Run tests:

npm run test

Lint code to check for style issues:

npm run lint

版本与发布记录

@croct/json5-parser 共发布 5 个版本,首次发布于 2025/03/01;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.2.2latest2025/12/0111 个月前
0.2.12025/08/291.2 年前
0.2.02025/08/281.2 年前
0.1.12025/05/171.5 年前
0.1.02025/03/011.7 年前

关于 @croct/json5-parser 的常见问题

@croct/json5-parser 是什么?

A lossless JSON5 tokenizer and parser for Node.js that maintains indentation, spacing, and comments.

如何安装 @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 和提交记录判断。