Parses and serializes configuration text with syntax beyond standard JSON.
Downloads / mo 1.2B
Stars 7.2K
Last release 2.2.3
License MIT Strengths Accepts configuration comments . Keep single-line or multi-line comments in configuration files. Reads standard JSON too . Parse existing valid JSON files without converting their syntax. Limitations Targets human-edited configuration . Use JSON for machine-to-machine communication. $ npm install json5@2.2.3 Copy
const JSON5 = require('json5');
const config = JSON5.parse('{ enabled: true, }');
JSON5 examples From open-source projects on GitHub export function parseConfigOverrides(configOverrides: string): any {
const trimmed = configOverrides.trim();
if (!trimmed) {
return {};
}
return JSON5.parse(trimmed);
}
Stringifies objects with their keys in sorted order for a deterministic result.
Downloads / mo 811.8M
Last release 2.1.0
License MIT Strengths Custom key comparison . A comparison function sets the order of object keys in the output. $ npm install fast-json-stable-stringify@2.1.0 Copy
const stringify = require('fast-json-stable-stringify');
const text = stringify({ b: 2, a: 1 });
fast-json-stable-stringify examples From open-source projects on GitHub async contentHash(): Promise<string> {
const content: Record<string, unknown> = { ...this.getContent() };
if (this.evaluators && this.evaluators.length > 0) {
content["evaluators"] = this.evaluators;
}
if (
this.executionPolicy &&
Object.keys(this.executionPolicy).length > 0
) {
content["executionPolicy"] = this.executionPolicy;
}
// Use fast-json-stable-stringify for deterministic JSON
const json = stringify(content);
// Use xxhash32 with a seed value for hashing
const hashFn = await initHashApi();
const hash = hashFn.h32(json, 0xabcd).toString(16);
return hash;
}
Show full example Serializes and restores circular object structures using a paired wire format.
Downloads / mo 797.9M
Stars 1.2K
Last release 3.4.4
License ISC Strengths Restores circular object links . Pair stringify and parse to round-trip recursive structures. Filters values during serialization . Pass a replacer to control which values stringify emits. Limitations Requires its matching parser . Pair flatted output with flatted.parse to restore references correctly. Supports JSON-compatible values only . Objects such as sockets do not round-trip as their original classes. $ npm install flatted@3.4.4 Copy
const { stringify } = require('flatted');
const value = {};
value.self = value;
const text = stringify(value);
flatted examples From open-source projects on GitHub export function useWhyDidYouUpdate(
name: string,
props: Record<string, any>,
{
onChangeFound,
onNoChangeFound,
}: {
onChangeFound?: (data: {
changesObj: Record<
string,
{ from: any; to: any; isDeepEqual: boolean; changedKeys?: string[] }
>
}) => void
onNoChangeFound?: () => void
} = {},
) {
const latestProps = useRef(props)
useEffect(() => {
if (!__DEV__) return
const allKeys = Object.keys({ ...latestProps.current, ...props })
const changesObj: Record<
string,
{ from: any; to: any; isDeepEqual: boolean; changedKeys?: string[] }
> = {}
allKeys.forEach((key) => {
if (latestProps.current[key] !== props[key]) {
changesObj[key] = {
from: latestProps.current[key],
to: props[key],
changedKeys:
props[key] && typeof props[key] === 'object'
? Object.keys(latestProps.current[key])
.map((k) =>
latestProps.current[key][k] === props[key][k] ? '' : k,
)
.filter(Boolean)
: undefined,
isDeepEqual: _.isEqual(latestProps.current[key], props[key]),
}
}
})
if (Object.keys(changesObj).length) {
if (onChangeFound) {
onChangeFound({ changesObj })
} else {
// eslint-disable-next-line no-console
console.log('[why-did-you-update]', name, {
changes: flatted.parse(flatted.stringify(changesObj)),
props: { from: latestProps.current, to: props },
})
}
} else if (onNoChangeFound) {
onNoChangeFound()
}
latestProps.current = props
})
}
Show full example Parses JSON and throws errors that show the failing line in a code frame.
Downloads / mo 727.1M
Last release 8.3.0
License MIT Strengths Names the source file . An optional filename appears in the error message. Limitations Throws on invalid JSON . A parsing error throws a JSONError rather than returning a partial value. $ npm install parse-json@8.3.0 Copy
import parseJson from 'parse-json';
const value = parseJson('{"enabled":true}');
parse-json examples From open-source projects on GitHub export function parse(jsonString, file = '') {
try {
return parseJson(jsonString);
} catch (e) {
throw new Error(`${file} - ${e.message}`);
}
}
Stringifies objects deterministically without the unlicensed jsonify dependency.
Downloads / mo 700.0M
Last release 1.0.1
License MIT Strengths Consistent hashes . Equal objects produce the same string and the same hash. $ npm install json-stable-stringify-without-jsonify@1.0.1 Copy
const stringify = require('json-stable-stringify-without-jsonify');
const text = stringify({ b: 2, a: 1 });
json-stable-stringify-without-jsonify examples From open-source projects on GitHub function hashOfConfigFor(config) {
if (!configHashCache.has(config)) {
configHashCache.set(
config,
hash(`${pkg.version}_${nodeVersion}_${stringify(config)}`),
);
}
return configHashCache.get(config);
}
Show full example Clones and serializes values with types beyond JSON, including recursive data, as a structuredClone polyfill.
Downloads / mo 493.6M
Last release 1.4.0
License ISC Strengths Serialized output is JSON-safe . Recursive values pass through JSON.stringify and deserialize intact. Limitations No Blob or File support . Blob, File, ImageBitmap, and other non-JavaScript types are not supported yet. $ npm install @ungap/structured-clone@1.4.0 Copy
import { stringify } from '@ungap/structured-clone/json';
const text = stringify({ any: 'serializable' });
@ungap/structured-clone examples From open-source projects on GitHub async importDID(args: IIdentifier) {
const oldTree = deserialize(serialize(this.cacheTree, { lossy: true }))
this.cacheTree.dids[args.did] = args
args.keys.forEach((key) => {
this.cacheTree.keys[key.kid] = {
...key,
// FIXME: keys should be able to associate with multiple DIDs
meta: { ...key.meta, did: args.did },
}
})
await this.notifyUpdate(oldTree, this.cacheTree)
return true
}
Show full example Scans, parses, and edits JSON with JavaScript-style comments.
Downloads / mo 414.0M
Last release 3.3.1
License MIT Strengths Computes document edits . The modify API returns edits that insert, remove, or replace a value in a document. Limitations Parses past errors . The error list, rather than an exception, reports invalid input. $ npm install jsonc-parser@3.3.1 Copy
const { parse } = require('jsonc-parser');
const errors = [];
const value = parse('{ /* configuration */ "enabled": true }', errors);
if (errors.length) throw new Error('Invalid JSONC');
jsonc-parser examples From open-source projects on GitHub export function writeJsonConfig(
filePath: string,
config: ConfigFile,
configKey: string,
): void {
const dir = dirname(filePath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
let originalContent = "";
let existingConfig: ConfigFile = {};
if (existsSync(filePath)) {
originalContent = readFileSync(filePath, "utf-8");
// jsonc.parse returns undefined for empty and comment-only files.
const parsed: unknown = jsonc.parse(originalContent);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
existingConfig = parsed as ConfigFile;
}
}
// Copilot CLI ignores root keys once mcpServers exists. Fold a bare map
// into mcpServers before writing that wrapper, or those servers vanish.
const replaceDocument =
configKey !== ROOT_CONFIG_KEY && isBareServerMap(existingConfig);
if (replaceDocument) {
existingConfig = { mcpServers: { ...existingConfig } };
}
dropReplacedServers(existingConfig, config, configKey);
const mergedConfig = deepMerge(existingConfig, config);
if (originalContent) {
try {
const configKeyPath = replaceDocument ? [] : jsoncPath(configKey);
const newValue = replaceDocument
? mergedConfig
: getNestedValue(mergedConfig, configKey);
const edits = jsonc.modify(originalContent, configKeyPath, newValue, {
formattingOptions: detectIndent(originalContent),
});
const updatedContent = jsonc.applyEdits(originalContent, edits);
writeFileSync(filePath, updatedContent);
return;
} catch {
// jsonc-parser failed, fall back to JSON.stringify
}
}
writeFileSync(filePath, JSON.stringify(mergedConfig, null, 2));
}
Show full example Stringifies values deterministically and handles circular structures and BigInt instead of throwing.
Downloads / mo 363.2M
Last release 3.0.1
License MIT Strengths No dependencies . The package installs with no dependencies in ESM or CommonJS projects. Limitations Circular references become placeholders . Each circular reference becomes the configured placeholder value in the output. $ npm install safe-stable-stringify@3.0.1 Copy
const stringify = require('safe-stable-stringify');
const text = stringify({ b: 2, a: 1 });
safe-stable-stringify examples From open-source projects on GitHub _doRequest(options, callback, auth, path) {
// Prepare options for outgoing HTTP request
const headers = Object.assign({}, this.headers);
if (auth && auth.bearer) {
headers.Authorization = `Bearer ${auth.bearer}`;
}
const req = (this.ssl ? https : http).request({
...this.options,
method: 'POST',
host: this.host,
port: this.port,
path: `/${path.replace(/^\//, '')}`,
headers: headers,
auth: (auth && auth.username && auth.password) ? (`${auth.username}:${auth.password}`) : '',
agent: this.agent
});
req.on('error', callback);
req.on('response', res => (
res.on('end', () => callback(null, res)).resume()
));
const jsonStringify = configure({
...(this.maximumDepth && { maximumDepth: this.maximumDepth })
});
req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8'));
}
Show full example