@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
What is JSONC? Jump to heading
JSONC (JSON with Comments) is a variant of JSON that allows comments and trailing commas. It is commonly used for configuration files where human readability and maintainability are important, such as in Visual Studio Code settings files.
Why use @std/jsonc? Jump to heading
This package allows you to easily parse JSONC files, which are not supported by the standard JSON parser. It is useful for reading configuration files that may contain comments or trailing commas, making them more user-friendly.
Examples Jump to heading
Parse with comments and trailing commas
import { parse } from "@std/jsonc";
const text = `{
// Service config
"host": "localhost",
"port": 8000, // trailing comma allowed
}`;
const cfg = parse(text);
// => { host: "localhost", port: 8000 }
Merge user config over defaults
import { parse } from "@std/jsonc";
const defaults = { host: "127.0.0.1", port: 3000 } as const;
const userText = `{
// Only override port
"port": 8080,
}`;
const user = parse(userText) as Partial<typeof defaults>;
const finalCfg = { ...defaults, ...user };
// => { host: "127.0.0.1", port: 8080 }
Load a .jsonc file in Deno
import { parse } from "@std/jsonc";
const raw = await Deno.readTextFile("config.jsonc");
let cfg: unknown;
try {
cfg = parse(raw);
} catch (err) {
// Surface a clean error; JSONC parser points near the syntax location
throw new Error(`Failed to parse config.jsonc: ${err.message}`);
}
Strip comments to plain JSON (if you must emit JSON)
// There is no JSONC stringify yet. To emit JSON, remove comments, then JSON.stringify
function stripJsonc(input: string): string {
// Remove /* */ and // comments (naive). Ensure you don't remove content inside strings in critical cases.
return input
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/(^|[^:])\/\/.*$/gm, "$1");
}
const clean = stripJsonc(raw);
const obj = JSON.parse(clean);
Tips Jump to heading
- Only parsing is supported; for writing, strip comments or use plain JSON.
- Be strict when reading untrusted input—JSONC is for config, not wire protocols.
- When stripping comments, be careful with naive regex in the presence of string literals. Prefer keeping JSONC at rest and converting only when necessary.