{"record":{"id":"6e874e5983fede27","repo":"microsoft/aspire","slug":"json-patch-array-index-indextext-is-invalid-for-an-array","errorCode":null,"errorMessage":"JSON Patch array index '{indexText}' is invalid for an array with {count} elements.","messagePattern":"JSON Patch array index '(.+?)' is invalid for an array with (.+?) elements\\.","errorType":"exception","errorClass":"JsonException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting/Dcp/JsonPatch.cs","lineNumber":293,"sourceCode":"                target.RemoveAt(index);\n                break;\n            case \"replace\":\n                target[index] = value?.DeepClone();\n                break;\n        }\n    }\n\n    private static int ParseArrayIndex(string indexText, int count, bool allowEnd)\n    {\n        if (indexText.Length == 0 ||\n            (indexText.Length > 1 && indexText[0] == '0') ||\n            !indexText.All(char.IsAsciiDigit) ||\n            !int.TryParse(indexText, NumberStyles.None, CultureInfo.InvariantCulture, out var index) ||\n            index < 0 ||\n            index > count ||\n            (!allowEnd && index == count))\n        {\n            throw new JsonException($\"JSON Patch array index '{indexText}' is invalid for an array with {count} elements.\");\n        }\n\n        return index;\n    }\n}\n","sourceCodeStart":275,"sourceCodeEnd":299,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting/Dcp/JsonPatch.cs#L275-L299","documentation":"ParseArrayIndex validates the final segment of a JSON Patch array path. The segment must be all ASCII digits, parse as a non-negative int, and be within bounds; unless allowEnd is set (i.e. the '-' token case for append), the index must also be strictly less than the array length. Any violation throws this JsonException with the index text and array size.","triggerScenarios":"Patching '/containers/5' when the array has 3 elements; passing a non-numeric segment like 'name' where an array index is expected; using index equal to Count where append ('-') is required.","commonSituations":"Hardcoded indexes after the array shrank; off-by-one errors treating index==Count as valid outside of 'add'; addressing arrays by property-style names.","solutions":["Check the array Count before patching and clamp/adjust the index","Use the '-' segment with an 'add' operation to append instead of computing Count","Fix the segment to an existing index or a property name if the target is actually an object"],"exampleFix":"// before\nnew JsonPatchOperation(\"add\", \"/containers/\" + containers.Count, item) // invalid: index == Count\n// after\nnew JsonPatchOperation(\"add\", \"/containers/-\", item) // '-' appends per RFC 6902","handlingStrategy":"validation","validationCode":"static bool IsValidArrayIndex(JsonArray array, string segment, bool allowEnd = false) {\n    if (segment == \"-\") return allowEnd;\n    return segment.All(char.IsAsciiDigit) && int.TryParse(segment, out var i) && i >= 0 && i < array.Count;\n}","typeGuard":null,"tryCatchPattern":"try { patcher.Apply(doc, operations); }\ncatch (JsonException ex) when (ex.Message.Contains(\"array index\")) {\n    logger.LogWarning(ex, \"Bad array index in patch path; use '-' to append\");\n}","preventionTips":["Use the '-' segment to append rather than computing Count","Recheck array length after any operation that mutates the array","Never reuse hardcoded indexes across resource revisions"],"tags":["json-patch","array-index","out-of-range","json"],"backgroundTag":"index-out-of-range","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}