On this page
@std/jsonc
Overview Jump to heading
Provides tools for working with JSONC (JSON with comments).
Currently, this module only provides a means of parsing JSONC. JSONC serialization is not yet supported.
import { parse } from "@std/jsonc";
import { assertEquals } from "@std/assert";
assertEquals(parse('{"foo": "bar", } // comment'), { foo: "bar" });
assertEquals(parse('{"foo": "bar", } /* comment *\/'), { foo: "bar" });
Add to your project Jump to heading
deno add jsr:@std/jsonc
See all symbols in @std/jsonc on
什么是 JSONC? Jump to heading
JSONC(带注释的 JSON)是一种 JSON 的变体,允许添加注释和尾随逗号。它通常用于需要强调人类可读性和维护性的配置文件中,比如 Visual Studio Code 的设置文件。
为什么使用 @std/jsonc? Jump to heading
该包允许你轻松解析 JSONC 文件,而标准的 JSON 解析器不支持。它适用于读取可能包含注释或尾随逗号的配置文件,使其更具用户友好性。
示例 Jump to heading
解析带注释和尾随逗号的内容
import { parse } from "@std/jsonc";
const text = `{
// 服务配置
"host": "localhost",
"port": 8000, // 允许尾随逗号
}`;
const cfg = parse(text);
// => { host: "localhost", port: 8000 }
将用户配置合并到默认配置上
import { parse } from "@std/jsonc";
const defaults = { host: "127.0.0.1", port: 3000 } as const;
const userText = `{
// 只覆盖端口
"port": 8080,
}`;
const user = parse(userText) as Partial<typeof defaults>;
const finalCfg = { ...defaults, ...user };
// => { host: "127.0.0.1", port: 8080 }
在 Deno 中加载 .jsonc 文件
import { parse } from "@std/jsonc";
const raw = await Deno.readTextFile("config.jsonc");
let cfg: unknown;
try {
cfg = parse(raw);
} catch (err) {
// 抛出清晰的错误;JSONC 解析器会提示语法位置附近
throw new Error(`解析 config.jsonc 失败:${err.message}`);
}
剥离注释以生成纯 JSON(如果必须输出 JSON)
// 目前还没有 JSONC 的 stringify。要输出 JSON,先去除注释,然后用 JSON.stringify
function stripJsonc(input: string): string {
// 移除 /* */ 和 // 注释(简单处理)。注意关键情况要避免删除字符串内部内容。
return input
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/(^|[^:])\/\/.*$/gm, "$1");
}
const clean = stripJsonc(raw);
const obj = JSON.parse(clean);
小贴士 Jump to heading
- 目前仅支持解析;写入时,请去除注释或使用纯 JSON。
- 读取不受信任的输入时应严格对待 —— JSONC 适合配置,不适合传输协议。
- 去除注释时,简单的正则表达式在遇到字符串字面量时可能不安全。建议保持 JSONC 格式,仅在必要时转换。