← All articles

Fix "[object Object] is Not Valid JSON" and Other JSON Syntax Errors

Getting "[object Object] is not valid JSON" or "expected a JSON object, array or literal"? Learn why these errors happen, how to correct JSON syntax, fix trailing commas, and repair broken JSON automatically.

You run your code, check the network tab, and see it: "[object Object]" is not valid JSON. Or maybe your JSON validator says Expected a JSON object, array or literal, or your parser chokes on a comma after the last element. These errors are among the most common — and most confusing — JSON mistakes developers encounter. This guide explains exactly what each error means, why it happens, and how to correct JSON syntax so your parser accepts it.

What Does "[object Object] is Not Valid JSON" Mean?

When JavaScript converts an object to a string without using JSON.stringify(), the result is the text [object Object] — the default output of every object's .toString() method. If that string then gets passed to JSON.parse() or sent as a request body, you get the error:

SyntaxError: "[object Object]" is not valid JSON

The parser is trying to parse the literal text [object Object]. It sees [, expects a JSON array, finds the unquoted word object, and fails. The bracket is real — it is the first character of the string [object Object] — but what follows is not valid JSON array syntax.

Why Does [object Object] Appear in JSON?

The root cause is always the same: a JavaScript object was coerced to a string somewhere in the code before being parsed or transmitted. Here are the four most common ways this happens:

String concatenation

When you concatenate an object with a string, JavaScript calls .toString() on the object, which returns [object Object]:

const user = { name: "Alice", age: 30 };

// ❌ String concatenation coerces the object
const body = "data=" + user;
console.log(body); // "data=[object Object]"

// ✅ Use JSON.stringify
const body = "data=" + JSON.stringify(user);

fetch / XMLHttpRequest body without JSON.stringify

Passing a plain object as the body of a fetch call converts it to a string automatically:

const payload = { action: "login", user: "alice" };

// ❌ fetch coerces the object to "[object Object]"
fetch('/api/login', {
  method: 'POST',
  body: payload,
});

// ✅ Serialize first, set Content-Type
fetch('/api/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(payload),
});

Template literals

Embedding an object directly in a template literal calls .toString():

const config = { theme: "dark", lang: "en" };

// ❌ Template literal coercion
const json = `{"config": ${config}}`;
// '{"config": [object Object]}'  ← invalid JSON

// ✅ Stringify just the object
const json = `{"config": ${JSON.stringify(config)}}`;
// '{"config": {"theme":"dark","lang":"en"}}'

Nested stringify

Calling JSON.stringify() on an object that already contains a pre-serialized JSON string as a value produces double-encoded output — the string literal appears inside the JSON rather than the object it represents:

const inner = JSON.stringify({ id: 1 }); // '{"id":1}'
const outer = JSON.stringify({ data: inner });
// '{"data":"{\"id\":1}"}' — the data field is a string, not an object

// If that outer string is then JSON.parse()'d and data is used as JSON again,
// you need to JSON.parse(result.data) a second time.

How to Fix the [object Object] JSON Error

The fix is always to ensure the object is serialised with JSON.stringify() before being used as a string or transmitted over the network. A quick diagnostic: search your code for every place the affected variable is used as a string and add JSON.stringify() at that point.

// Systematic fix pattern
function toJsonBody(obj) {
  if (typeof obj === 'string') {
    // Already a string — validate it is valid JSON before using
    JSON.parse(obj); // throws if invalid
    return obj;
  }
  return JSON.stringify(obj);
}

"Expected a JSON Object, Array or Literal" — What This Means

This error comes from Firefox's built-in JSON viewer (and some JSON validators) and means the top-level value in your JSON is not any of the six valid JSON types. Common causes:

  • The input is an empty string.JSON.parse("") throws this error because an empty string is not a valid JSON value.
  • The input is undefined. JSON.stringify(undefined) returns undefined (not the string"undefined"), and JSON.parse(undefined) throws.
  • The response is HTML, not JSON. A server error page often returns HTML. The first character < is not valid JSON. Check the Content-Type header and the raw response body in the Network tab before assuming the JSON itself is broken.
  • There is a BOM at the start of the file. A UTF-8 BOM (bytes 0xEF 0xBB 0xBF) prepended to a JSON file causes this error in strict parsers. RFC 8259 explicitly prohibits BOMs in JSON.
// Guard against empty / undefined before parsing
function safeParse(text) {
  if (!text || typeof text !== 'string') {
    throw new TypeError(`Cannot parse ${typeof text} as JSON`);
  }
  return JSON.parse(text.trimStart()); // trimStart removes accidental BOM/whitespace
}

JSON Comma After Last Element: The Trailing Comma Error

Another extremely common JSON syntax error is a trailing comma — a comma that appears after the last item in an object or array:

// ❌ Trailing comma in object
{
  "name": "Alice",
  "age": 30,
}

// ❌ Trailing comma in array
["red", "green", "blue",]

JSON's grammar requires a comma to separate two items — it must always have a value on both sides. A comma with nothing after it violates the grammar. JavaScript itself allows trailing commas (since ES5), which is why developers often write them without thinking.

To find and fix trailing commas programmatically:

// ⚠️ Regex fix — works for simple cases, can corrupt strings
const fixed = raw.replace(/,\s*([}\]])/g, '$1');

// ✅ Better: use a repair parser that understands the grammar
// e.g. the json-repair library on npm

For a deep dive into this specific error, see Trailing Comma in JSON: Why it Throws and How to Fix It.

How to Correct JSON Syntax: A Complete Checklist

Before reaching for a JSON corrector tool, run through this checklist to identify the class of error:

Structure

  • Every { has a matching } and every [ has a matching ]. Unclosed brackets are one of the most common truncation errors.
  • No trailing commas — no comma after the last key–value pair in an object or the last item in an array.
  • No missing commas — every item in an object or array (except the last) must be followed by a comma.

Strings

  • All strings use double quotes. Single-quoted strings ('Alice') are JavaScript syntax, not JSON.
  • All object keys are double-quoted strings. Bare keys ({ name: "Alice" }) are JavaScript object literal syntax, not JSON.
  • Control characters inside strings are escaped. Raw newlines, tabs, and null bytes inside a JSON string are illegal — use \n, \t, instead.

Values

  • Booleans are lowercase:true / false, not True / False / TRUE.
  • Null is lowercase:null, not None, nil, or NULL.
  • No undefined. JSON has no undefined type; use null or omit the key entirely.
  • No NaN or Infinity. These JavaScript values have no JSON representation. JSON.stringify({x: Infinity}) produces {"x":null}, silently.

Extra content

  • No comments.// line comments and /* block comments */ are not part of the JSON specification.
  • No trailing content. A valid JSON text is exactly one value — nothing before it (except optional whitespace) and nothing after it.

Using a JSON Corrector: When to Automate

For one-off debugging, fixing JSON by hand is fast. For production pipelines that receive JSON from external sources — APIs, AI model outputs, user input — you need a JSON corrector: code or a tool that programmatically repairs common syntax errors without breaking valid content.

A good JSON corrector handles:

  • Trailing commas in objects and arrays
  • Single-quoted strings → double-quoted strings
  • Unquoted keys → double-quoted keys
  • Python literals (True, False, None) → JSON equivalents
  • JavaScript // line and /* block */ comments → removed
  • Markdown code fences (```json ... ```) → stripped
  • Unclosed brackets → auto-closed

The key requirement is that corrections are grammar-aware — the tool understands which tokens are structural separators and which are inside string values, so it never corrupts string content that happens to contain ,} or True.

For a walkthrough of how to implement JSON repair in JavaScript code, see How to Handle Broken JSON in JavaScript.

Avoiding JSON.stringify Pitfalls (Including Circular References)

Once you start always serializing with JSON.stringify, two situations still trip people up:

  • Circular references throw. A value like const a = {}; a.self = a; gives TypeError: Converting circular structure to JSON. Three good alternatives: drop the back-reference with a custom replacer that tracks seen objects; switch to structuredClone(value) for in-memory deep copies; or use a library like flatted when you genuinely need to serialize a cyclic graph and reconstruct it later.
  • Lossy types.JSON.stringify silently drops undefined, functions, and Symbol values, and converts NaN / Infinity to null. Convert these into something representable before stringify, not after parsing.

Quick Reference: Common JSON Errors and Fixes

// 1. [object Object] — object coerced to string
❌ fetch(url, { body: myObject })
✅ fetch(url, { body: JSON.stringify(myObject) })

// 2. Trailing comma
❌ { "a": 1, "b": 2, }
✅ { "a": 1, "b": 2 }

// 3. Single quotes
❌ { 'name': 'Alice' }
✅ { "name": "Alice" }

// 4. Unquoted key
❌ { name: "Alice" }
✅ { "name": "Alice" }

// 5. Python boolean
❌ { "active": True }
✅ { "active": true }

// 6. Comment in JSON
❌ { "debug": true // log everything }
✅ { "debug": true }

// 7. Empty string
❌ JSON.parse("")
✅ JSON.parse(text || "null")

// 8. HTML error page as "JSON"
❌ JSON.parse("<!DOCTYPE html>...")
✅ Check response.ok and Content-Type before calling response.json()

Frequently Asked Questions

What does "[object Object] is not valid JSON" mean?

A JavaScript object was converted to a string with its default .toString(), producing the literal text [object Object], and that text was then parsed or sent as JSON. The fix is to serialise with JSON.stringify() before using the value as a string.

How do I fix the [object Object] error in a fetch request?

Set body: JSON.stringify(payload) and add a Content-Type: application/json header. Passing a raw object as the body coerces it to [object Object].

What is "Expected a JSON object, array or literal"?

Firefox and some validators print this when the top-level value isn't one of the six JSON types — usually because the input is empty, undefined, HTML instead of JSON, or starts with a byte-order mark. Check response.ok and the Content-Type header first.

What are the most common JSON syntax errors?

Trailing commas, single quotes, unquoted keys, Python literals (True/None), comments, and NaN/Infinity. Each has a dedicated guide: see trailing commas, unexpected-token errors, unexpected end of input, and bad control characters.

Fix JSON Syntax Online — No Setup Required

If you have a broken JSON string you need to correct right now, JSON Fix repairs all of the errors above automatically. Paste your JSON — however broken — click Repair & Format, and get back syntactically correct, formatted JSON. The tool runs entirely in your browser: no data is sent to any server, making it safe for sensitive payloads.