The message "invalid top-level element array" almost always means a tool expected a single object (or a specific root element) at the top of a document, but it found a JSON array instead. To fix it, find the consumer that reads the data, confirm what shape it requires, and either wrap the array in an object, select one item, or switch to a format or parser that permits a top-level array. The correct fix depends on which layer raised the error: strict JSON-RPC, an XML/HTML parser, a schema validator, or a framework binding format. Each has different rules, and applying the wrong one—such as adding a wrapper object when the consumer is actually an XML parser—won't help.

This guide walks through identifying the failing layer, applying the appropriate patch, and verifying the result with a concrete check.

Start by confirming which layer rejects the array

Before editing any file, trace where the error originates. The phrase appears in several unrelated contexts, and the fix is different for each. A quick way to narrow it is to look at the error's companions: stack trace filenames, the name of the parser or library, and the surrounding text.

JSON-RPC and some API clients. JSON-RPC 2.0 requires the top-level value to be a single request or response object, not an array. Libraries like Newtonsoft.Json's JsonRpcClient or certain transport layers throw "invalid top-level element" when the payload begins with [. Batch requests exist but must use the specific batch format the server accepts. XML and HTML. Well-formed XML needs exactly one root element. A fragment with multiple sibling elements—often produced by concatenating strings—parses as an invalid document. Browsers' DOMParser in application/xml mode, or Java's DocumentBuilder, will raise a parse error in that case. JSON Schema and OpenAPI validation. A schema whose root type is object rejects an input array. Validators report this as a type mismatch at the top level. Framework-specific deserializers. Some Java/Kotlin libraries (Jackson, Gson) throw a variant of "cannot deserialize from Array value" or "invalid top-level element" when the expected type is an object. This is technically a shape mismatch, not a syntax error.

Match the error to its reader. If you see JsonRpc in the stack, treat it as JSON-RPC. If you see SAXParseException or "Content is not allowed in prolog," treat it as XML. Guessing wrong and adding a wrapper object to an XML payload, for example, won't resolve anything and may create new errors.

Prerequisites you should gather first

A few inexpensive checks prevent wasted edits:

1: Capture the exact error text and stack trace. Copy it, don't paraphrase. The library name and file path point to the layer. 2: Save a copy of the failing payload. Print the first 200 characters of the raw string to confirm what actually reaches the parser—Whitespace, a byte-order mark (BOM), or a leading log line often mascarades as a shape error. 3: Confirm the expected contract. Read the API docs, schema, or partner spec for what the root value should be. 4: Note the tool's version. Behavior differs: some REST clients accept a top-level array as the default response, while strict JSON-RPC never does.

Once you have the trace, the raw payload, and the contract, you're ready to apply a fix.

Fix 1: Wrap a JSON array in an object when the consumer expects an object

This is the most common and safe fix. If a client or validator expects a root object, wrap the array in a named property. For example, if your current payload looks like:

Change it to:

Then update the consumer to read .items. The property name must match what the schema or API expects; data, results, value, or items are common conventions. Read the spec, don't invent a name.

Success check. Re-run the request or validation. A successful parse returns the array inside the expected property. A failure may now report a missing property or different type, which tells you the property name is wrong.

Gson's equivalent for Java is to deserialize to a Wrapper class rather than List. Jackson's fix is ObjectMapper.readValue(json, new TypeReference<Wrapper>() {}). Kotlinx.serialization requires an @Serializable wrapper class. The wrapper concept is universal; only the code changes.

Fix 2: Handle JSON-RPC batches correctly

JSON-RPC 2.0's specification states that a request is a single object with jsonrpc, method, and optionally params and id. It permits batches, but only as an array of request objects, which some clients implement separately from single calls. If your client library throws "invalid top-level element" when it sees [, the payload is probably being sent to a non-batch endpoint or a client configured for single calls.

Steps:

1: Inspect whether the server exposes a batch endpoint or accepts the array as the whole request. 2: If it does, use the library's batch method (for example, JsonRpcBatchRequest in some .NET libraries) rather than sending an array through the single-call method. 3: If not, iterate the array on the client side and send one request per element, correlating responses by id.

Stop condition. If you can't confirm the server accepts batches, don't send arrays. Silent partial failures—where the server returns only some responses—are harder to debug than a clean error.

Fix 3: Repair an XML or HTML document with a single root

XML requires exactly one root element containing everything else. If you're producing XML by string concatenation, you may be emitting sibling elements at the top:

That is not a document. Wrap it:

Steps to verify:

1: Confirm the parser mode: DOMParser().parseFromString(str, "application/xml") yields a document containing a parsererror element when the input is malformed. Check for that element rather than assuming success. 2: For HTML fragments, use text/html mode, which tolerates multiple top-level nodes and doesn't enforce a single root the way XML does. 3: For large inputs, validate with a schema or a well-formedness check before sending.

Success check. Re-parsing produces no parsererror (in browsers) or SAXParseException (in Java). You can independently check well-formedness by loading the file in a browser's XML viewer; a parse error appears inline.

Fix 4: Adjust the schema or validator

If the consumer is a JSON Schema validator whose root declares "type": "object", a top-level array is invalid by definition. Two legitimate remedies exist, and choosing between them is a design decision, not a syntax tweak:

Change the data. Wrap the array so the root becomes an object. This preserves the schema and is usually correct when the contract is externally owned. Change the schema. If your data genuinely is a list and the schema is under your control, set the root type to "array" and add an "items" definition. This is appropriate for internal APIs or standalone data files.

Don't mix the two: shipping an array against an object schema, then loosening the schema to "any," loses validation value. A worked example clarifies the trade-off. Suppose you publish a file that consumers load into a typed model. If existing consumers use model.items, adding a top-level array—even with a permissive schema—will break deserialization in Jackson, which expects a declared wrapper type. In that case, wrap the array. Conversely, a brand-new file with a declared array schema and no legacy consumers can stay an array.

Success check. Run the validator against a known-good and a known-bad sample. The good sample passes; the bad sample fails with a specific type error, not a generic one.

Common root causes

Knowing why the shape mismatch happens saves time on the next occurrence:

A logging or proxy layer added an array. Some gateways wrap responses in [...]; trace the byte stream, not just the source file. String concatenation in a loop. Building "pages" of XML or JSON by appending fragments accidentally creates a top-level array. Deserializing to the wrong type. If code declares List but the actual contract is {items: [...]}, a mapper throws a variant of the error. Align the type with the contract. A BOM at the start of the payload. Some parsers read a UTF-8 BOM as invalid content before the root. Strip it or read with the matching encoding. Multiple documents concatenated. This happens in stream processing; split or wrap them.

Troubleshooting the fix when it doesn't work

Symptom-first troubleshooting keeps you from re-editing the same line repeatedly.

The error persists after wrapping. The consumer may be reading the array from a different source—cache, environment variable, or fixture. Clear caches, restart the service, and confirm the payload on the wire. New error: "unexpected token." That points to syntax, not shape. Run the payload through a JSON or XML linter before the application parser. New error: "missing property." The wrapper name doesn't match the schema. Check the spec, not the error's suggestion. Error only in production. Check for a proxy or gateway that reformats the body. Compare the exact bytes received versus sent. Error only for large payloads. Some clients chunk the response; an array may be read as the first chunk. This is a proxy/parser issue, not your data's shape.

Reversible check order. Start with the cheapest changes: print the raw payload, then run a standalone parser on a copy, then modify the wrapper. This isolates the layer before touching application logic.

Stop condition. If the error comes from a vendor SDK or a closed-source validator and the contract is unclear, escalate to the vendor or the API owner. Guessing at an undocumented contract—alternating between wrapper names or schema relaxations—creates compatibility problems in other consumers. Don't iteratively loosen validation until errors disappear; a permissive schema masks real type errors downstream.

Edge cases worth knowing

Empty arrays. Some validators accept null but reject []; others require an empty object. Check the schema's minItems. A wrapper around an empty array may be the cleanest fix if null isn't permitted. Top-level arrays in YAML. YAML permits a sequence at the top of a document, so if the "parser" is actually YAML, the JSON-specific fix doesn't apply. The failure then belongs to the consuming application, not the syntax. JSON Lines (NDJSON). Each line is a JSON value; the file as a whole is not a JSON document. Parsers that read NDJSON line by line succeed where a single JSON.parse on the whole file fails. If that's the format, don't wrap the array—split lines. Encoding and BOM. UTF-8 with a BOM can trip strict parsers. Saving as plain UTF-8 often resolves spurious "invalid element" errors.

Verification you can rerun

A minimal check confirms the fix without relying on intuition:

1: Parse the payload with the actual consumer library in a scratch test—a unit test is ideal. 2: Assert the parsed root is an object (or a single root element) with the expected keys. 3: Assert a second, deliberately malformed payload fails with the correct error class. 4: For arrays with a wrapper, assert the count matches the source array.

If step 1 fails with the same message, you didn't change the right layer; go back to the trace. If step 3 fails to produce the expected error, the validation step is too permissive and won't catch future regressions.

The fix is narrow by design: one layer, one shape. Resist broad changes—such as rewriting the whole pipeline or switching libraries—until you've confirmed the root cause. Most "invalid top-level element array" errors resolve with a wrapper object, a correct parser mode, or a schema that matches the data's actual shape.