{"record":{"id":"7b9019af1116773c","repo":"jestjs/jest","slug":"cannot-parse-filepath-as-json-error-message","errorCode":null,"errorMessage":"Cannot parse ${filePath} as JSON: ${error.message}","messagePattern":"Cannot parse (.+?) as JSON: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/jest-haste-map/src/worker.ts","lineNumber":60,"sourceCode":"    if (content === undefined) {\n      content = fs.readFileSync(filePath, 'utf8');\n    }\n\n    return content;\n  };\n\n  if (filePath.endsWith(PACKAGE_JSON)) {\n    // Process a package.json that is returned as a PACKAGE type with its name.\n    try {\n      const fileData = JSON.parse(getContent());\n\n      if (fileData.name) {\n        const relativeFilePath = path.relative(rootDir, filePath);\n        id = fileData.name;\n        module = [relativeFilePath, H.PACKAGE];\n      }\n    } catch (error: any) {\n      throw new Error(`Cannot parse ${filePath} as JSON: ${error.message}`, {\n        cause: error,\n      });\n    }\n  } else if (!blacklist.has(filePath.slice(filePath.lastIndexOf('.')))) {\n    // Process a random file that is returned as a MODULE.\n    if (hasteImpl) {\n      id = hasteImpl.getHasteName(filePath);\n    }\n\n    if (computeDependencies) {\n      const content = getContent();\n      const extractor = data.dependencyExtractor\n        ? await requireOrImportModule<DependencyExtractor>(\n            data.dependencyExtractor,\n            false,\n          )\n        : defaultDependencyExtractor;\n      dependencies = [","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/jestjs/jest/blob/8e6d128e4a278059ecddecaa97400b04c8ae5fd9/packages/jest-haste-map/src/worker.ts#L42-L78","documentation":"The haste-map worker reads and JSON.parses every `package.json` it encounters during the crawl to extract the package name as a haste ID. If `JSON.parse` throws (malformed JSON, trailing comma, BOM, comments), the worker re-throws a descriptive Error naming the file and the parse error message, with the original error attached as `cause`. This stops processing of that file.","triggerScenarios":"worker() at worker.ts:49 checks `filePath.endsWith(PACKAGE_JSON)`, calls `JSON.parse(getContent())` at line 52, and the catch at line 59 re-throws the wrapped error at line 60. Any package.json with invalid JSON syntax triggers it.","commonSituations":"A hand-edited package.json with a trailing comma, single quotes, or a comment; a corrupted/truncated file from a failed git merge; a generated package.json with a NaN or unquoted key; node_modules package.json overwritten by a broken postinstall script.","solutions":["Open the file named in the error message and run it through a JSON validator or `npx jsonlint <file>`.","Fix the specific syntax error the embedded `${error.message}` describes (e.g. 'Unexpected token').","If the file is in node_modules, reinstall the offending package: `npm ci`.","Add the path to `modulePathIgnorePatterns` or `roots` exclusion if it is an unrelated generated file."],"exampleFix":"// before — broken package.json\n{\n  \"name\": \"my-pkg\",\n  \"version\": \"1.0.0\",   // trailing comma\n}\n// after\n{\n  \"name\": \"my-pkg\",\n  \"version\": \"1.0.0\"\n}","handlingStrategy":"type-guard","validationCode":"// Validate every package.json in the crawl path before building.\nimport { readFileSync } from 'node:fs';\nimport glob from 'fast-glob';\nfunction validatePackageJsons(rootDir: string) {\n  for (const file of glob.sync(`${rootDir}/**/package.json`, { ignore: '**/node_modules/**' })) {\n    try { JSON.parse(readFileSync(file, 'utf8')); }\n    catch (e) { throw new Error(`Invalid JSON in ${file}: ${(e as Error).message}`); }\n  }\n}","typeGuard":"function isValidJsonFile(filePath: string): boolean {\n  try { JSON.parse(readFileSync(filePath, 'utf8')); return true; }\n  catch { return false; }\n}","tryCatchPattern":null,"preventionTips":["Run a JSON lint pass on all package.json files in CI.","Add a pre-commit hook (e.g. `jsonlint`) for package.json edits.","Reinstall node_modules (`npm ci`) if a node_modules package.json is corrupt."],"tags":["json","package-json","worker","parse-error","configuration"],"backgroundTag":null,"analyzedSha":"8e6d128e4a278059ecddecaa97400b04c8ae5fd9","analyzedAt":"2026-08-10T18:11:27.960Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}