{"record":{"id":"d084dac273952475","repo":"swc-project/swc","slug":"failed-parse-json-as-javascript-object-err","errorCode":null,"errorMessage":"failed parse json as javascript object: {err:#?}","messagePattern":"failed parse json as javascript object: (.+?)","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"crates/swc_node_bundler/src/loaders/json.rs","lineNumber":17,"sourceCode":"use std::sync::Arc;\n\nuse anyhow::{anyhow, Error};\nuse swc_atoms::atom;\nuse swc_common::{SourceFile, DUMMY_SP};\nuse swc_ecma_ast::*;\nuse swc_ecma_parser::{parse_file_as_expr, Syntax};\n\npub(super) fn load_json_as_module(fm: &Arc<SourceFile>) -> Result<Module, Error> {\n    let expr = parse_file_as_expr(\n        fm,\n        Syntax::default(),\n        EsVersion::Es2020,\n        None,\n        &mut Vec::new(),\n    )\n    .map_err(|err| anyhow!(\"failed parse json as javascript object: {err:#?}\"))?;\n\n    let export = ExprStmt {\n        span: DUMMY_SP,\n        expr: AssignExpr {\n            span: DUMMY_SP,\n            op: op!(\"=\"),\n            left: MemberExpr {\n                span: DUMMY_SP,\n                obj: Box::new(Ident::new_no_ctxt(atom!(\"module\"), DUMMY_SP).into()),\n                prop: MemberProp::Ident(IdentName::new(atom!(\"exports\"), DUMMY_SP)),\n            }\n            .into(),\n            right: expr,\n        }\n        .into(),\n    }\n    .into();\n","sourceCodeStart":1,"sourceCodeEnd":35,"githubUrl":"https://github.com/swc-project/swc/blob/d7d74346665e36e692aa07e13d4ee3ee692ee35c/crates/swc_node_bundler/src/loaders/json.rs#L1-L35","documentation":"Thrown by swc_node_bundler's JSON loader: a .json module is parsed with parse_file_as_expr (Es2020 expression parser) to convert it into module.exports = {...}, and that parse failed. JSON is almost always a valid JS expression, so failure means the file contains content that is not strict JSON-as-expression.","triggerScenarios":"Bundling with the node bundler where a .json import contains top-level comments, trailing commas, NaN/Infinity/undefined literals, unquoted or duplicate-ish syntax, a BOM, or is actually JSONC/JSON5 - all rejected by the Es2020 parser.","commonSituations":"Projects mixing tsconfig-style commented JSON into files that get imported (e.g. importing a config written as JSONC), editor tooling saving with BOM, or generated files containing Infinity from serialization.","solutions":["Validate the file with a strict JSON parser (JSON.parse) and fix whatever it flags: remove comments, trailing commas, NaN/Infinity, quote keys","Rename true JSONC files to .jsonc/.json5 and keep them out of the bundler's json loader path, or pre-transpile them","Strip BOM before the file reaches the loader"],"exampleFix":"// data.json before (comment - invalid as JS expression source for strict JSON)\n// build config\n{ \"a\": 1, }\n\n// after\n{ \"a\": 1 }","handlingStrategy":"validation","validationCode":"// Rust: strict-parse JSON before it reaches the bundler\nfn json_is_strict(path: &Path) -> Result<(), String> {\n    let raw = std::fs::read_to_string(path).map_err(|e| e.to_string())?;\n    let trimmed = raw.trim_start_matches('\\u{feff}'); // strip BOM\n    serde_json::from_str::<serde_json::Value>(trimmed)\n        .map(|_| ())\n        .map_err(|e| format!(\"{} is not strict JSON: {e}\", path.display()))\n}","typeGuard":null,"tryCatchPattern":"match load_json_as_module(&fm) {\n    Err(e) if e.to_string().contains(\"failed parse json as javascript object\") => {\n        anyhow::bail!(\"file {} must be strict JSON (no comments/trailing commas/NaN)\", fm.name)\n    }\n    other => other,\n}","preventionTips":["Keep JSONC/JSON5 in .jsonc/.json5 files so loaders route them correctly","Lint imported .json files with a strict parser in CI","Configure editors to save JSON without BOM and without comment-style formatting"],"tags":["swc","bundler","json","loader","node"],"backgroundTag":null,"analyzedSha":"d7d74346665e36e692aa07e13d4ee3ee692ee35c","analyzedAt":"2026-08-16T12:41:13.160Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}