{"id":"4433e25861dd3383","repo":"serde-rs/json","slug":"no-entry-found-for-key","errorCode":null,"errorMessage":"no entry found for key","messagePattern":"no entry found for key","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/map.rs","lineNumber":479,"sourceCode":"\n/// Mutably access an element of this map. Panics if the given key is not\n/// present in the map.\n///\n/// ```\n/// # use serde_json::json;\n/// #\n/// # let mut map = serde_json::Map::new();\n/// # map.insert(\"key\".to_owned(), serde_json::Value::Null);\n/// #\n/// map[\"key\"] = json!(\"value\");\n/// ```\nimpl<Q> ops::IndexMut<&Q> for Map<String, Value>\nwhere\n    String: Borrow<Q>,\n    Q: ?Sized + Ord + Eq + Hash,\n{\n    fn index_mut(&mut self, index: &Q) -> &mut Value {\n        self.map.get_mut(index).expect(\"no entry found for key\")\n    }\n}\n\nimpl Debug for Map<String, Value> {\n    #[inline]\n    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n        self.map.fmt(formatter)\n    }\n}\n\n#[cfg(any(feature = \"std\", feature = \"alloc\"))]\nimpl serde::ser::Serialize for Map<String, Value> {\n    #[inline]\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: serde::ser::Serializer,\n    {\n        use serde::ser::SerializeMap;","sourceCodeStart":461,"sourceCodeEnd":497,"githubUrl":"https://github.com/serde-rs/json/blob/a3e9758ffc88247ab82182cb2505867768a702e3/src/map.rs#L461-L497","documentation":"This is a panic raised by serde_json's IndexMut impl for Map<String, Value> at src/map.rs:479. The line `self.map.get_mut(index).expect(\"no entry found for key\")` runs when you assign into a map via the `map[key] = value` syntax; if the key is not already present, get_mut returns None and expect aborts the process. It mirrors the panic semantics of BTreeMap/IndexMut: indexing is for read/write access to EXISTING entries, not for insertion. Use a fallible accessor (get_mut, entry, insert) when the key may be absent.","triggerScenarios":"Calling `obj[\"field\"] = json!(...)` or `&mut obj[\"field\"]` on a serde_json::Map / Value::Object whose key does not exist. Also reachable via `serde_json::Value` indexing when the inner object lacks the requested key. Differs from `Map::insert` (which creates the entry) and from `Map::get_mut` (which returns Option). The same syntax on serde_json::Value for a non-object variant yields a different panic (\"not an object\"), so this specific message always means: the Map lookup missed.","commonSituations":"1) Assuming a JSON payload always carries an optional field, then writing into it without inserting first. 2) Building up a response object field-by-field with `map[\"k\"] = v` instead of `insert`. 3) Schema/version drift: server stopped returning a key the client expected to mutate. 4) Typos or case mismatch in the key string (JSON keys are case-sensitive). 5) Mutating a Map produced from `Value::as_object_mut()` after the field was filtered/renamed upstream.","solutions":["Replace `map[key] = value` with `map.insert(key.to_owned(), value)` when you want to create-or-overwrite the entry.","Use `map.entry(key).or_insert(value)` when you want to ensure a default and then mutate the returned slot.","If you only want to mutate an existing entry, use `if let Some(slot) = map.get_mut(key) { *slot = value; }` to skip absent keys safely.","When the Map comes from a parsed Value, narrow it first: `if let Value::Object(map) = &mut val { ... }` and validate the key with `map.contains_key(key)` before indexing.","Audit the payload with a typed deserializer (serde_derive struct with Option<T> for optional fields) so missing keys surface as None instead of panicking on assignment."],"exampleFix":"// before — panics when \"timeout\" is absent\nlet mut v: serde_json::Value = serde_json::from_str(input)?;\nv[\"timeout\"] = serde_json::json!(30);\n\n// after — create-or-overwrite without panicking\nuse serde_json::Value;\nlet mut v: Value = serde_json::from_str(input)?;\nmatch v.as_object_mut() {\n    Some(map) => {\n        map.entry(\"timeout\".to_owned())\n            .or_insert(Value::Null);\n        map[\"timeout\"] = json!(30);\n    }\n    None => return Err(\"expected a JSON object\".into()),\n}","handlingStrategy":"validation","validationCode":"use serde_json::Map;\n\n/// Safe setter that never panics — inserts if missing, overwrites if present.\nfn ensure_set(map: &mut Map<String, serde_json::Value>, key: &str, val: serde_json::Value) {\n    map.insert(key.to_owned(), val);\n}\n\n/// Safe conditional mutate — no-op when the key is absent.\nfn mutate_existing(map: &mut Map<String, serde_json::Value>, key: &str, val: serde_json::Value) {\n    if let Some(slot) = map.get_mut(key) {\n        *slot = val;\n    }\n}\n\n/// Guard before indexing: refuse to call IndexMut unless key is present.\nfn check_before(map: &Map<String, serde_json::Value>, key: &str) -> bool {\n    map.contains_key(key)\n}","typeGuard":"use serde_json::{Map, Value};\n\n/// Narrows a Value to a mutable Object map; returns None for non-objects.\nfn as_object_mut_guard(v: &mut Value) -> Option<&mut Map<String, Value>> {\n    match v {\n        Value::Object(map) => Some(map),\n        _ => None,\n    }\n}\n\n/// Returns true only when indexing with this key is panic-safe.\nfn key_present(map: &Map<String, Value>, key: &str) -> bool {\n    map.contains_key(key)\n}","tryCatchPattern":null,"preventionTips":["Treat `map[key] = v` as a read-modify operation, not an insert — use `Map::insert` or `Map::entry` to create new keys.","Before destructuring a parsed Value with indexing, narrow with `as_object_mut()` and check `contains_key`.","Define the JSON contract with serde structs (Option<T> for optional fields) instead of ad-hoc Map mutation.","Add unit tests that exercise the absent-key path; the panic only fires at runtime under missing data.","Enable clippy::indexing_slicing (or forbid_unsafe-style discipline) in CI to catch indexing on Option-returning accessors."],"tags":["serde-json","rust","panic","indexmut","json-object","runtime"],"analyzedSha":"a3e9758ffc88247ab82182cb2505867768a702e3","analyzedAt":"2026-08-06T01:22:47.029Z","schemaVersion":2}