jestjs/jest · error · MalformedPackageJsonError
There is malformed json in
Error message
There is malformed json in ${packageJsonPath} What it means
create-jest reads and JSON.parses package.json before generating the Jest config; if parsing throws (syntax error, trailing comma, unquoted key, BOM, or empty file), it wraps the failure in MalformedPackageJsonError naming the offending path. The init cannot proceed because it needs to inspect `scripts.test` and the `jest`/`type` fields and may rewrite the file.
Solutions
- Run `node -e "JSON.parse(require('fs').readFileSync('package.json','utf8'))"` or `npx jsonlint package.json` to locate the exact syntax error and fix it.
- Re-run `jest --init` after the JSON parses cleanly.
- If the file was truncated, restore it from version control (`git checkout -- package.json`) and re-apply intended edits carefully.
Example fix
// before (package.json)
{
"name": "app",
"scripts": { "test": "jest", }, // trailing comma
}
// after
{
"name": "app",
"scripts": { "test": "jest" }
} Defensive patterns
Strategy: validation
Validate before calling
// Validate package.json parses before invoking jest --init.
import * as fs from 'node:fs';
function validatePackageJson(filePath) {
try {
JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (e) {
throw new Error(`${filePath} is not valid JSON: ${e.message}`);
}
}
// Or lint from the CLI: npx jsonlint package.json Type guard
function isValidPackageJson(raw: string): boolean {
try { JSON.parse(raw); return true; } catch { return false; }
} Prevention
- Lint package.json (e.g. `npx jsonlint package.json`) after manual edits.
- Avoid JSON5 features (comments, trailing commas) in package.json.
- Configure your editor to flag invalid JSON and to format on save.
- Add a CI step that JSON.parses package.json to catch corruption early.
When it happens
Trigger: `jest --init` while package.json contains invalid JSON: trailing commas, single-quoted strings, comments, a stray character, or a zero-byte file. The try/catch around JSON.parse(readFileSync(...)) catches any throw and rethrows this error.
Common situations: Hand-edited package.json with a JSON5 feature (comments/trailing commas) not valid in strict JSON; a botched merge/rebase leaving a conflict marker or duplicate key; a file accidentally overwritten or truncated; copy-pasting config snippets with unquoted keys.
Understand the failure class
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
AI-assisted analysis of jestjs/jest@8e6d128e4a (2026-08-10).
Data as JSON: /api/errors/cbc3984422c1e85f.
Report an issue: GitHub.
Appendix: source
Thrown at packages/create-jest/src/runCreate.ts:68
export async function runCreate(rootDir = process.cwd()): Promise<void> {
rootDir = tryRealpath(rootDir);
// prerequisite checks
const projectPackageJsonPath = path.join(rootDir, PACKAGE_JSON);
if (!fs.existsSync(projectPackageJsonPath)) {
throw new NotFoundPackageJsonError(rootDir);
}
const questions = [...defaultQuestions];
let hasJestProperty = false;
let projectPackageJson: ProjectPackageJson;
try {
projectPackageJson = JSON.parse(
fs.readFileSync(projectPackageJsonPath, 'utf8'),
) as ProjectPackageJson;
} catch {
throw new MalformedPackageJsonError(projectPackageJsonPath);
}
if (projectPackageJson.jest) {
hasJestProperty = true;
}
const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext =>
fs.existsSync(path.join(rootDir, getConfigFilename(ext))),
);
if (hasJestProperty || existingJestConfigExt != null) {
const result: {continue: boolean} = await prompts({
initial: true,
message:
'It seems that you already have a jest configuration, do you want to override it?',
name: 'continue',
type: 'confirm',
});View on GitHub (pinned to 8e6d128e4a)