ENRU

Mismatched bracket in JSON: “Expected … after array element”

Updated

Wrong bracket. Wrong door. Objects close with }, arrays with ], and the closing bracket must match the most recent one still open. [1} and {"a": 1] fail for that reason alone, and the real mistake is usually a bracket missing a few lines earlier.

The error and the fix

An array inside an object, and its ] went missing:

{
  "id": "op-0042",
  "tags": ["quiet", "fast",
  "mercy": false
}

Read it the way a parser does. After "fast", it expects one more array element, gets "mercy", then a colon where an array allows only a comma or ]. Chrome and Python ask for a comma at that colon, line 4 column 10, and this site’s validator calls the colon an unexpected character. The fix is on line 3:

{
  "id": "op-0042",
  "tags": ["quiet", "fast"],
  "mercy": false
}

The clean case, where the parser meets the wrong closing bracket itself, looks like {"tags": ["quiet", "fast"}. Either way, the place to fix is where the open bracket should have closed, not where the error appeared.

Why the closing bracket must match

RFC 8259 pairs the brackets in the grammar itself: object = begin-object [ member *( value-separator member ) ] end-object, array = begin-array [ value *( value-separator value ) ] end-array. An object ends only with } (end-object), an array only with ] (end-array), and containers nest, so the innermost open one must close first. There is no rule that lets } close an array, and no parser guesses which bracket you meant.

Mismatched bracket error messages by parser

The two smallest cases: [1} and {"a": 1]. Several parsers don’t report a mismatch at all but the comma they would have accepted instead.

ParserArray closed with }: [1}Object closed with ]: {"a": 1]
Chrome, Edge, Node.js (V8)Expected ',' or ']' after array element in JSON at position 2 (line 1 column 3)Expected ',' or '}' after property value in JSON at position 7 (line 1 column 8)
Node.js 18, older Chrome (V8 10.2)Unexpected token } in JSON at position 2Unexpected token ] in JSON at position 7
FirefoxJSON.parse: expected ',' or ']' after array element at line 1 column 3 of the JSON dataJSON.parse: expected ',' or '}' after property value in object at line 1 column 8 of the JSON data
SafariJSON Parse error: Expected ']'JSON Parse error: Expected '}'
PythonExpecting ',' delimiter: line 1 column 3 (char 2)Expecting ',' delimiter: line 1 column 8 (char 7)
Go (encoding/json)invalid character '}' after array elementinvalid character ']' after object key:value pair
Java (Jackson 2)Unexpected close marker '}': expected ']', plus where the array startedUnexpected close marker ']': expected '}', plus where the object started
C# (System.Text.Json)'}' is invalid without a matching open.']' is invalid without a matching open.
C# (Newtonsoft.Json)JsonToken EndObject is not valid for closing JsonType Array. Path '', line 1, position 3.JsonToken EndArray is not valid for closing JsonType Object. Path '', line 1, position 8.
PHP (json_decode)State mismatch (invalid or malformed JSON), json_last_error() 2State mismatch (invalid or malformed JSON), json_last_error() 2
Rust (serde_json)expected , or ] at line 1 column 3expected , or } at line 1 column 8
jqjq: parse error: Objects must consist of key:value pairs at line 1, column 3jq: parse error: Unmatched ']' at line 1, column 8

Jackson, Newtonsoft.Json and PHP are the ones that actually call it a mismatch; PHP even gives it its own error code, 2, instead of the generic 4. System.Text.Json’s “without a matching open” is misleading: there is an open bracket, just of the other kind. Checked by running: Node.js 18, 24 and 25.1, Safari 27, Python 3.9 and 3.14, Go 1.25–1.27, Jackson 2.22 and 3.2, System.Text.Json and Newtonsoft.Json 13.0.4, PHP 8.3 and 8.5, serde_json 1.0, jq 1.7 and 1.8; Firefox from its source code and Mozilla’s reference.

  • An extra closing bracket at the end, {"a": 1}}. The document was complete after the first }; whatever follows is extra data (“Unexpected non-whitespace character after JSON” in Chrome, “Extra data” in Python).
  • A closing bracket with nothing open, such as ] at the very start. Nothing to mismatch with, so it is an unexpected character.
  • A bracket where a value should be, {"a": } or [1, , 2]. The bracket is of the right kind, the value is missing: also an unexpected character.
  • No closing bracket at all: the input ends first. That is an unclosed bracket.

How to locate the wrong bracket in code

A parser tells you where it met the wrong bracket. You also want the bracket it was trying to close; the Python snippet finds both with a stack, and the others show what each library gives you directly.

Python

pairs = {"}": "{", "]": "["}

def mismatch(text):
    """First closing bracket that does not match, with the bracket it should close."""
    stack, in_string, i = [], False, 0
    while i < len(text):
        c = text[i]
        if in_string:
            if c == "\\":
                i += 1
            elif c == '"':
                in_string = False
        elif c == '"':
            in_string = True
        elif c in "{[":
            stack.append(i)
        elif c in "}]":
            if stack and text[stack[-1]] == pairs[c]:
                stack.pop()
            else:
                return {"closer": i, "opener": stack[-1] if stack else None}
        i += 1
    return None

print(mismatch('{"tags": ["quiet", "fast"}'))  # {'closer': 25, 'opener': 9}

JavaScript

const text = '{"tags": ["quiet", "fast"}';
try {
  JSON.parse(text);
} catch (e) {
  const pos = Number(/position (\d+)/.exec(e.message)?.[1]);
  console.log(text[pos], e.message); // } Expected ',' or ']' after array element in JSON at position 25 (line 1 column 26)
}

Go

package main

import (
	"encoding/json"
	"errors"
	"fmt"
)

func main() {
	text := `{"tags": ["quiet", "fast"}`
	var v any
	err := json.Unmarshal([]byte(text), &v)
	var se *json.SyntaxError
	if errors.As(err, &se) {
		// Offset is just past the bad byte.
		fmt.Printf("%c at byte %d: %v\n", text[se.Offset-1], se.Offset-1, err)
	}
}

Java (Jackson)

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

try {
    new ObjectMapper().readTree("{\"tags\": [\"quiet\", \"fast\"}");
} catch (JsonProcessingException e) {
    // Names both brackets, then adds where the array started.
    System.out.println(e.getOriginalMessage().split(" \\(")[0]);
}

C#

using System.Text.Json;

try {
    JsonDocument.Parse("{\"tags\": [\"quiet\", \"fast\"}");
} catch (JsonException e) {
    Console.WriteLine(e.BytePositionInLine); // 25, counted from zero, in bytes
}

PHP

json_decode('{"tags": ["quiet", "fast"}');
// 2 is the dedicated mismatch code; most other syntax errors are 4.
echo json_last_error(), ' ', json_last_error_msg(); // 2 State mismatch (invalid or malformed JSON)

How to keep brackets matched

  • Edit nested JSON in an editor that highlights bracket pairs, and format the document after every larger edit: wrong nesting shows up as wrong indentation.
  • When you cut a block, cut it from its opening bracket to its own closing one, never line by line.
  • Don’t assemble nested JSON from string fragments; build the structure and serialize it.
  • Check the result in the JSON validator before it travels further.

Try it in the validator

Open a sample with a mismatched bracket in the JSON validator. It reports mismatched_bracket at the wrong closing bracket, and the “Opened at line L, column C” button takes you to the bracket it should have closed.

Related: unclosed bracket, extra data, missing comma, unexpected character, and all JSON errors.

Mismatched bracket FAQ

What does “Expected … after array element” mean in Chrome?

An array element ended and V8 could accept only a comma or ]. It found something else: often } closing the array by mistake, sometimes a missing comma before the next element.

What is “State mismatch (invalid or malformed JSON)” in PHP?

PHP’s name for a closing bracket that doesn’t match the open one, json_last_error() code 2. Look for } where ] belongs or the other way round.

Why is the error far from the real mistake?

A forgotten bracket only becomes an error when the parser meets a bracket of the other kind, which can be many lines later. Find the opening bracket the error refers to and check where it should have closed.