If you got an error like:
SyntaxError: Unexpected token } in JSON at position 42
or
SyntaxError: Trailing comma in JSON
and looking at your JSON you found a comma right before a } or ], that’s exactly it: a trailing comma is one of the most common causes of invalid JSON, especially for people coming from JavaScript, where it’s allowed.
What a trailing comma is
It’s an extra comma left after the last item in an object or array, right before the closing bracket.
// json
{
"name": "test",
"age": 30,
}
Notice the comma after "age": 30. There’s nothing after it before the } closes. That’s invalid JSON.
Same goes for arrays:
// json
[
"item1",
"item2",
]
The comma after "item2" also breaks the parse.
Why this happens so often
In plain JavaScript (not JSON), a trailing comma is allowed and even encouraged by many linters, since it makes it easier to add or remove items without touching the previous line.
// valid javascript
const obj = {
name: "test",
age: 30,
};
The problem shows up when that JavaScript object gets turned into a string and treated as JSON, or when someone writes JSON by hand out of JavaScript habit. The JSON spec (defined in RFC 8259) simply doesn’t allow trailing commas, so the parser rejects them.
How to fix it
Just remove the comma from the last item.
// json
{
"name": "test",
"age": 30
}
// json
[
"item1",
"item2"
]
Sounds simple, but when the JSON is large or generated dynamically (for example, by concatenating strings in a loop), it’s easy to miss.
A common mistake: building JSON by concatenating strings in a loop
// javascript
// Generates JSON with an unwanted trailing comma
let json = "{";
items.forEach(item => {
json += `"${item.key}": "${item.value}",`;
});
json += "}";
If the loop runs at least once, a comma is left dangling before the final }. The right fix here isn’t trying to strip the comma manually at the end of the string. It’s using JSON.stringify() instead of building the string by hand.
// javascript
const obj = {};
items.forEach(item => {
obj[item.key] = item.value;
});
const json = JSON.stringify(obj); // always generates valid JSON
That avoids the problem at the root, since JSON.stringify() never leaves a trailing comma behind.
Quick checklist
- Check the last item in every object
{}and array[]in your JSON - No comma after the last value, right before the closing bracket?
- If the JSON is generated dynamically, consider using
JSON.stringify()instead of concatenating strings manually - For large files, paste it into JSON Formatter & Validator to find the exact position without scanning line by line