{"record":{"id":"9adc3748dac1120e","repo":"BoundaryML/baml","slug":"baml-json-deserialize-failed-e","errorCode":null,"errorMessage":"baml.json.deserialize failed: {e:?}","messagePattern":"baml\\.json\\.deserialize failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"baml_language/crates/baml_exec/src/dispatch.rs","lineNumber":293,"sourceCode":"}\n\n/// Coerce JSON text into a typed BAML value via the stdlib's\n/// `baml.json.deserialize<T>` (which dispatches user `from_json` overrides).\nasync fn deserialize_via_baml_json(\n    engine: &Arc<BexEngine>,\n    json_text: &str,\n    ty: &RuntimeTy,\n    helper_context: &HelperCallContext,\n) -> Result<BexExternalValue> {\n    let result = engine\n        .call_function(\n            \"baml.json.deserialize\",\n            vec![BexExternalValue::String(json_text.into())],\n            helper_context.call_context(indexmap::IndexMap::from([(\"T\".to_string(), ty.clone())])),\n            true,\n        )\n        .await\n        .map_err(|e| anyhow!(\"baml.json.deserialize failed: {e:?}\"))?;\n    Ok(result)\n}\n\n#[cfg(test)]\nmod tests {\n    use baml_type::TyAttr;\n    use bex_engine::BexEngine;\n    use sys_native::SysOpsExt;\n\n    use super::*;\n\n    fn engine(source: &str) -> Arc<BexEngine> {\n        let snapshot = baml_tests::engine::compile_source(source);\n        Arc::new(\n            BexEngine::new(snapshot, Arc::new(sys_native::SysOps::native()), Vec::new())\n                .expect(\"BexEngine::new should succeed\"),\n        )\n    }","sourceCodeStart":275,"sourceCodeEnd":311,"githubUrl":"https://github.com/BoundaryML/baml/blob/bd85ce9dee1463ff04d27efd20531013a4ff46c1/baml_language/crates/baml_exec/src/dispatch.rs#L275-L311","documentation":"Argument coercion routes every value through the engine's own `baml.json.deserialize` helper (a BAML-level function invoked with the target type as `T`). If that internal call fails - malformed JSON text, value not coercible to `T` - the error is wrapped with this message including the debug-formatted engine error.","triggerScenarios":"`deserialize_via_baml_json` awaits the helper call and maps any failure to `baml.json.deserialize failed: {e:?}`; triggered by per-arg JSON text from `--json-args` that doesn't parse or doesn't match the declared parameter type.","commonSituations":"Passing a string where an int is expected, malformed nested JSON inside `--json-args`, or enum values that don't match declared variants during auto-CLI dispatch.","solutions":["Inspect the wrapped debug error for the underlying coercion failure (bad JSON text vs type mismatch).","Validate each field in `--json-args` against the parameter's declared type and enum variants.","Test the payload parses as valid JSON (`jq .`) before dispatching.","Use `--json-args @file` with a verified file to rule out shell quoting mangling the JSON."],"exampleFix":"// before\nbaml run myFunc -- --json-args '{\"count\": \"three\"}'  // count: int\n\n// after\nbaml run myFunc -- --json-args '{\"count\": 3}'","handlingStrategy":"try-catch","validationCode":"// pre-validate each --json-args field parses cleanly\nlet v: serde_json::Value = serde_json::from_str(field_text)\n    .map_err(|e| format!(\"param {name}: invalid JSON: {e}\"))?;","typeGuard":null,"tryCatchPattern":"match result {\n    Err(e) if e.to_string().contains(\"baml.json.deserialize failed\") => {\n        eprintln!(\"argument coercion failed; check JSON values against declared types: {e:?}\");\n    }\n    other => other,\n}","preventionTips":["Match each --json-args field to its declared parameter type and enum variants","Validate payloads with jq before dispatch","Avoid shell quoting that mangles embedded JSON; prefer @file for complex payloads","Keep helper `baml.json.deserialize` semantics in mind when changing param types"],"tags":["json","deserialization","type-mismatch","baml"],"backgroundTag":"json-unmarshal-failed","analyzedSha":"bd85ce9dee1463ff04d27efd20531013a4ff46c1","analyzedAt":"2026-09-12T03:38:25.718Z","contentChangedAt":"2026-09-12T03:38:25.718Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}