How do I fix invalid JSON before sending an API request?

The fastest way to fix invalid JSON is to validate it before sending the request, then correct the first syntax error the parser reports. Most failures come from a small set of mistakes: trailing commas, single quotes, unquoted keys, comments, or JavaScript values that JSON does not support.

This is especially useful when you are copying an object from JavaScript, editing an API payload by hand, or debugging a response that suddenly stopped parsing. JSON looks simple, but it is stricter than JavaScript object syntax.

What does valid JSON actually look like?

Valid JSON has a limited set of data types: objects, arrays, strings, numbers, booleans, and null.

A basic object looks like this:

{
  "name": "Alice",
  "age": 24,
  "active": true
}

Object keys and string values use double quotes. Objects use curly braces, arrays use square brackets, and individual properties are separated with commas.

Arrays can contain multiple values:

{
  "languages": [
    "JavaScript",
    "Python",
    "Go"
  ]
}

The important distinction is that JSON is a data format, not arbitrary JavaScript. Code that looks perfectly reasonable inside a JavaScript file can still be invalid JSON.

Why does my JSON have a trailing comma error?

A trailing comma appears when you put a comma after the final property of an object or the final item of an array.

This is invalid:

{
  "name": "Alice",
  "age": 24,
}

The comma after 24 tells the parser that another property should follow. The closing brace arrives instead, so parsing fails.

Remove the final comma:

{
  "name": "Alice",
  "age": 24
}

The same rule applies to arrays.

Invalid:

[
  "apple",
  "banana",
]

Valid:

[
  "apple",
  "banana"
]

This is one reason JSON can behave differently from JavaScript. Modern JavaScript allows trailing commas in many situations, but standard JSON does not.

Why does single-quoted JSON fail?

This is another common mistake when copying a JavaScript object.

The following is not valid JSON:

{
  'name': 'Alice',
  'city': 'Kathmandu'
}

Replace the single quotes with double quotes:

{
  "name": "Alice",
  "city": "Kathmandu"
}

JSON requires double quotes around property names and string values.

This distinction matters when you copy data from a programming language. Python, JavaScript, and other languages have their own syntax rules, while JSON has its own specification.

If you are working with an actual JavaScript object, you may not need to manually rewrite it. You can serialize it with JSON.stringify():

const user = {
  name: "Alice",
  city: "Kathmandu"
};

const json = JSON.stringify(user);

console.log(json);

The resulting string is valid JSON.

Why are unquoted keys invalid?

JavaScript allows this:

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

But JSON requires the keys to be quoted:

{
  "name": "Alice",
  "age": 24
}

If you paste a JavaScript object directly into an API request that expects JSON, the unquoted keys can cause a parse error.

Do not fix this by randomly adding quotes around every word. Nested objects, arrays, strings, and values need to remain structurally correct.

For example:

{
  "user": {
    "name": "Alice"
  },
  "roles": [
    "admin",
    "editor"
  ]
}

Only the property names require quotes. The strings inside the array require quotes because they are string values.

Can JSON contain comments?

Standard JSON does not support comments.

This is invalid:

{
  "name": "Alice",
  // The user's display name
  "active": true
}

The same applies to block comments:

{
  "name": "Alice" /* display name */
}

If you need comments in a configuration file, you may actually be working with a different format such as JSONC or JSON5. Those formats add conveniences that standard JSON deliberately does not include.

That distinction is important. Removing comments is appropriate when the destination requires standard JSON; changing the file format may be better when humans need to maintain the configuration regularly.

What is the difference between JSON and a JavaScript object?

They look similar because JSON syntax was derived from JavaScript object notation, but they are not interchangeable.

A JavaScript object can contain things JSON cannot represent:

const data = {
  name: "Alice",
  created: new Date(),
  getName() {
    return this.name;
  }
};

A JSON document cannot contain functions or a Date object as JavaScript types.

To send the data as JSON, convert supported values into JSON-compatible representations:

const data = {
  name: "Alice",
  created: new Date().toISOString()
};

const body = JSON.stringify(data);

There is another important limitation: undefined, NaN, Infinity, functions, BigInt, circular references, and several other JavaScript-specific values cannot simply be represented as standard JSON values.

If you are debugging an API request, inspect the serialized JSON rather than assuming the original JavaScript object is what actually gets transmitted.

How do I find the exact character causing the error?

Start with the first error reported by the parser.

If the message says something like:

Unexpected token } in JSON at position 42

do not immediately rewrite the entire document. Look around the reported position and inspect the surrounding property, comma, quote, or bracket.

A formatting tool can make this considerably easier because minified JSON hides the structure.

For example, this:

{"user":{"name":"Alice","roles":["admin","editor"]},"active":true}

is difficult to scan when the payload is much larger.

Formatted JSON makes the hierarchy visible:

{
  "user": {
    "name": "Alice",
    "roles": [
      "admin",
      "editor"
    ]
  },
  "active": true
}

Once the structure is visible, mismatched brackets and misplaced commas are much easier to spot.

How can I validate JSON without writing a script?

Paste the payload into Toolorah's JSON Formatter and use its validation or formatting controls. It can format readable JSON, minify valid JSON, and identify syntax problems such as trailing commas, single quotes, and unquoted keys.

For a normal API payload, that is usually faster than creating a temporary script just to discover whether a comma is in the wrong place.

There is a practical limitation, though: the tool's own guidance recommends using a local editor or command-line tool for very large JSON files. A browser formatter is convenient for ordinary payloads, but it should not be your only option for multi-megabyte datasets.

How do I validate JSON in JavaScript?

If your application receives JSON as a string, use JSON.parse() inside a try/catch.

function parseJson(input) {
  try {
    return JSON.parse(input);
  } catch (error) {
    console.error("Invalid JSON:", error.message);
    return null;
  }
}

const data = parseJson('{"name":"Alice","age":24}');

console.log(data);

This lets your application handle malformed input instead of crashing at the point where parsing occurs.

When creating JSON from a JavaScript object, use JSON.stringify():

const payload = {
  username: "alice",
  active: true,
  roles: ["admin", "editor"]
};

const json = JSON.stringify(payload);

console.log(json);

That separation is useful to remember:

  • JSON.stringify() converts a JavaScript value into a JSON string.
  • JSON.parse() converts a valid JSON string back into a JavaScript value.

Do not use eval() as a shortcut for parsing JSON. Apart from being unnecessary, evaluating arbitrary text as JavaScript creates a completely different security problem.

What should I check if the JSON looks correct but the API still rejects it?

A syntax-valid JSON document can still be an invalid API payload.

For example, this is valid JSON:

{
  "username": "alice",
  "age": 24
}

But an API might require userName instead of username, require age to be a string, or require another mandatory field entirely.

JSON validation answers one question: Is this valid JSON?

It does not answer: Does this JSON satisfy this API's schema?

If the parser accepts your payload but the server returns 400 Bad Request, inspect the API documentation and the server's response body. The problem may be the field names, data types, required properties, authentication, endpoint, or business rules rather than JSON syntax.

How do I compare two JSON responses?

Format both responses before comparing them.

Suppose one environment returns:

{"user":{"id":42,"name":"Alice","active":true}}

while another returns:

{"user":{"id":42,"name":"Alice","active":false}}

The meaningful difference is buried when the payloads are minified. After formatting, a normal line-by-line diff makes the changed value obvious.

This is also useful when debugging frontend and backend changes. If a request worked yesterday and fails today, compare the actual payloads rather than comparing the code that generated them.

For more specialized developer tasks, you can also use Toolorah's Developer Tools collection, which includes utilities for JSON, regular expressions, URL encoding, hashing, and other common debugging jobs.

What if the data is JSON Lines instead of normal JSON?

Do not assume every file containing JSON-shaped objects is one JSON document.

Normal JSON might look like:

[
  {"id": 1, "name": "Alice"},
  {"id": 2, "name": "Bob"}
]

JSON Lines, often called NDJSON or JSONL, instead stores one complete JSON value per line:

{"id":1,"name":"Alice"}
{"id":2,"name":"Bob"}

Those are different formats. A standard JSON parser expects the first example to be one complete document, while JSON Lines is designed so individual records can be processed separately.

This distinction becomes particularly important with logs and large datasets. If a parser says an otherwise sensible file is invalid, check whether you are actually dealing with JSONL rather than ordinary JSON.

How do I avoid breaking JSON while editing it?

The safest approach is to let your editor or formatter handle indentation and validation, and make small changes rather than rewriting large sections manually.

Keep these rules nearby when debugging:

  1. Use double quotes for keys and string values.
  2. Do not leave trailing commas.
  3. Do not add JavaScript comments to standard JSON.
  4. Quote object keys.
  5. Use null instead of undefined.
  6. Keep objects inside {} and arrays inside [].
  7. Check that every opening bracket or brace has a matching closing one.
  8. Remember that valid JSON does not automatically mean a valid API payload.

If the data is generated by your own JavaScript application, prefer JSON.stringify() over manually constructing a JSON string. If the data comes from an external API, inspect the raw response and validate it before changing anything.

That workflow catches syntax problems early without confusing JSON rules with the separate requirements imposed by the API receiving the data.