{"record":{"id":"a0bf46c93d21ba98","repo":"json-path/JsonPath","slug":"can-only-add-to-an-array","errorCode":null,"errorMessage":"Can only add to an array","messagePattern":"Can only add to an array","errorType":"exception","errorClass":"InvalidModificationException","httpStatus":null,"severity":"error","filePath":"json-path/src/main/java/com/jayway/jsonpath/internal/PathRef.java","lineNumber":181,"sourceCode":"\n        public void convert(MapFunction mapFunction, Configuration configuration){\n            Object currentValue = configuration.jsonProvider().getArrayIndex(parent, index);\n            configuration.jsonProvider().setArrayIndex(parent, index, mapFunction.map(currentValue, configuration));\n        }\n\n        public void delete(Configuration configuration){\n            configuration.jsonProvider().removeProperty(parent, index);\n        }\n\n        public void add(Object value, Configuration configuration){\n            Object target = configuration.jsonProvider().getArrayIndex(parent, index);\n            if(targetInvalid(target)){\n                return;\n            }\n            if(configuration.jsonProvider().isArray(target)){\n                configuration.jsonProvider().setProperty(target, null, value);\n            } else {\n                throw new InvalidModificationException(\"Can only add to an array\");\n            }\n        }\n\n        public void put(String key, Object value, Configuration configuration){\n            Object target = configuration.jsonProvider().getArrayIndex(parent, index);\n            if(targetInvalid(target)){\n                return;\n            }\n            if(configuration.jsonProvider().isMap(target)){\n                configuration.jsonProvider().setProperty(target, key, value);\n            } else {\n                throw new InvalidModificationException(\"Can only add properties to a map\");\n            }\n        }\n\n        @Override\n        public void renameKey(String oldKeyName, String newKeyName, Configuration configuration) {\n            Object target = configuration.jsonProvider().getArrayIndex(parent, index);","sourceCodeStart":163,"sourceCodeEnd":199,"githubUrl":"https://github.com/json-path/JsonPath/blob/62a4c9f0f65ba3f625aa0867d64c528ba72d09ec/json-path/src/main/java/com/jayway/jsonpath/internal/PathRef.java#L163-L199","documentation":"PathRef.add() appends a value to the JSON array located by an index-based path. Jayway JsonPath only supports the 'add' mutation when the target element is an array; if the element resolved at [parent, index] is a map, scalar, or null-like invalid value it is not silently converted, so the library throws InvalidModificationException(\"Can only add to an array\").","triggerScenarios":"Calling JsonPath.parse(...).add(path, value) (or PathRef.add via a mutation template) where the path's INDEX-based variant resolves to a non-array element — e.g. the element at the given array index is an object `{}` or a string, not a `[...]`.","commonSituations":"Document shape differs from expectations: developer assumes `$.items[0]` is an array but the API returns an object at that position; using `.add()` on a path that actually points at a map when `put()` was intended; schema drift after an upstream API version change.","solutions":["Verify the target element is a JSON array (jsonProvider().isArray / target instanceof List) before calling add().","If the target is an object, use put(key, value) instead of add(value).","Check the path itself: an index-based PathRef is the wrong ref type if the element is a map; adjust the path or use a property-based ref.","Wrap the mutation in try/catch for InvalidModificationException to handle divergent documents gracefully."],"exampleFix":"// before\ncontext.add(\"$.items[0]\", newItem); // throws if items[0] is an object\n// after\nObject target = context.read(\"$.items[0]\");\nif (target instanceof List) {\n    context.add(\"$.items[0]\", newItem);\n} else {\n    context.put(\"$.items[0]\", \"item\", newItem);\n}","handlingStrategy":"type-guard","validationCode":"Object el = context.read(\"$.items[0]\");\nif (!(el instanceof List)) throw new IllegalStateException(\"$.items[0] is not an array\");\ncontext.add(\"$.items[0]\", value);","typeGuard":"private static boolean isArray(Object o) { return o instanceof List; }","tryCatchPattern":"try { context.add(path, value); } catch (InvalidModificationException e) { log.warn(\"add() target at {} is not an array\", path); }","preventionTips":["Validate the element type at the path with read() before any add() call.","Use put() for objects and add() for arrays; never interchange them.","Pin a JSON schema for documents and validate before mutating.","Catch InvalidModificationException around mutations of externally sourced documents."],"tags":["json-path","mutation","type-mismatch"],"backgroundTag":"unsupported-operation","analyzedSha":"62a4c9f0f65ba3f625aa0867d64c528ba72d09ec","analyzedAt":"2026-09-11T11:36:00.448Z","contentChangedAt":"2026-09-11T11:36:00.448Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}