{"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    }\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 = [\n        ...extractor.extract(\n          content,","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/jestjs/jest/blob/f49721c78e195558b40913977c9230f5b7f559d8/packages/jest-haste-map/src/worker.ts#L42-L78","documentation":"The haste-map worker reads each file ending in package.json and JSON.parses its contents to extract the package `name`. If parsing fails it wraps the underlying SyntaxError into a clear Error naming the offending file path, so a single corrupt package.json does not produce an opaque JSON parse stack. The throw is in worker.ts:60 inside the catch of the JSON.parse try block.","triggerScenarios":"worker() detects filePath.endsWith(PACKAGE_JSON) (worker.ts:49), reads the file content via graceful-fs, and JSON.parse(getContent()) throws — e.g. trailing commas, comments, BOM, truncation, or a JSON5 file misnamed package.json. The catch at line 59 rethrows as `Cannot parse <filePath> as JSON: <error.message>`.","commonSituations":"A package.json edited by hand with a trailing comma or comment; a package.json written as JSON5/JSONC; a corrupted/partially-written file from a crashed install; symlinked package.json whose target is empty; BOM-prefixed file from a Windows tool.","solutions":["Open the path in the error message and validate it with a JSON linter or `node -e \"JSON.parse(require('fs').readFileSync('PATH','utf8'))\"`.","Remove JSON-incompatible syntax (comments, trailing commas, unquoted keys) or rename the file so haste-map does not treat it as package.json.","Strip a leading UTF-8 BOM if present.","If the file is intentionally JSON5, give it a different name so it is not discovered as a package manifest."],"exampleFix":"// before — package.json with a trailing comma (invalid JSON)\n{\n  \"name\": \"my-pkg\",\n  \"version\": \"1.0.0\",\n}\n\n// after — valid JSON\n{\n  \"name\": \"my-pkg\",\n  \"version\": \"1.0.0\"\n}","handlingStrategy":"validation","validationCode":"import {readFileSync} from 'node:fs';\nfunction assertValidPackageJson(filePath: string) {\n  if (!filePath.endsWith('package.json')) return;\n  const txt = readFileSync(filePath, 'utf8');\n  try { JSON.parse(txt); }\n  catch (e) { throw new Error(`${filePath} is not valid JSON: ${(e as Error).message}`); }\n}","typeGuard":null,"tryCatchPattern":"try {\n  JSON.parse(content);\n} catch (err) {\n  throw new Error(`Cannot parse ${filePath} as JSON: ${(err as Error).message}`);\n}","preventionTips":["Lint all package.json files in pre-commit (e.g. jsonlint).","Avoid JSON5/JSONC content in files named package.json — rename if needed.","Validate package.json after programmatic generation/edits."],"tags":["haste-map","json","package-json","worker","parse-error"],"analyzedSha":"f49721c78e195558b40913977c9230f5b7f559d8","analyzedAt":"2026-08-03T20:16:28.571Z","schemaVersion":2}