DevToolBoxGRATIS
Blogg

JSON Parse Error: Unexpected Token — Hitta och fixa

7 min läsningby DevToolBox

If you have ever seen SyntaxError: Unexpected token when parsing JSON, you are not alone. This is the single most common JSON error across JavaScript, Python, Go, and every other language. The good news: JSON syntax is simple, and the fix is almost always one of ten common mistakes. This guide shows you every error pattern, the exact fix, and the best debugging tools to prevent it from happening again.

1. What "Unexpected Token" Means in JSON

When a JSON parser encounters a character that violates the JSON specification, it throws an error with the position and the offending character. The error message varies by runtime:

JavaScript (Browser/Node.js):

SyntaxError: Unexpected token ' in JSON at position 1

Python:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Go:

invalid character '\'' looking for beginning of value

Java (Jackson):

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('\'' (code 39)): was expecting double-quote to start field name

All of these messages mean the same thing: your JSON is not valid. The parser found a character that is not allowed at that position according to the JSON specification (RFC 8259).

JSON is stricter than JavaScript object literals. It requires double quotes for keys and strings, does not allow trailing commas, does not support comments, and only accepts a small set of value types: string, number, boolean (true/false), null, object, and array.

2. Top 10 JSON Syntax Errors (With Before/After Fixes)

Error 1: Trailing Commas

JSON does not allow a comma after the last item in an object or array. JavaScript does, which is why this mistake is so common.

WRONG:

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

Error: Unexpected token } in JSON at position 28

FIXED:

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

Error 2: Single Quotes Instead of Double Quotes

JSON requires double quotes (") for all strings and keys. Single quotes (') are not valid JSON.

WRONG:

{'name': 'Alice', 'age': 30}

Error: Unexpected token ' in JSON at position 1

FIXED:

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

Error 3: Unquoted Keys

In JavaScript, object keys do not need quotes. In JSON, every key must be a double-quoted string.

WRONG:

{name: "Alice", age: 30}

Error: Expected property name or '}' in JSON at position 2

FIXED:

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

Error 4: Comments in JSON

The JSON specification does not allow comments. No //, no /* */, no #. If you need comments, use JSONC or JSON5 (see Section 6).

WRONG:

{
  // This is a comment
  "name": "Alice",
  /* multi-line
     comment */
  "age": 30
}

Error: Unexpected token / in JSON at position 2

FIXED (remove comments):

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

Error 5: undefined, NaN, Infinity

JSON only supports null as a special value. undefined, NaN, and Infinity are JavaScript-specific and not valid JSON.

WRONG:

{
  "value": undefined,
  "score": NaN,
  "limit": Infinity
}

Error: Unexpected token u in JSON at position 12

FIXED:

{
  "value": null,
  "score": 0,
  "limit": 9999999
}

Error 6: Extra/Missing Commas Between Items

Missing a comma between items or having a double comma both cause parse errors.

WRONG (missing comma):

{
  "name": "Alice"
  "age": 30
}

WRONG (double comma):

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

Error: Expected ',' or '}' in JSON at position 18

FIXED:

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

Error 7: Wrong Brackets (Mixing {} and [])

Using square brackets where curly braces are needed (or vice versa) is a common copy-paste error.

WRONG:

["name": "Alice", "age": 30]

Error: Expected property name or '}' in JSON at position 1

FIXED:

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

Error 8: BOM (Byte Order Mark) Character

Some text editors (especially on Windows) prepend an invisible UTF-8 BOM character (\uFEFF) to the beginning of files. This invisible character causes JSON parsing to fail.

WRONG (invisible BOM at start):

\uFEFF{"name": "Alice"}   ← invisible BOM character before {

Error: Unexpected token \uFEFF in JSON at position 0

FIXED (strip BOM before parsing):

// JavaScript: strip BOM before parsing
const clean = jsonString.replace(/^\uFEFF/, '');
const data = JSON.parse(clean);

// Node.js: read file and strip BOM
const fs = require('fs');
const raw = fs.readFileSync('data.json', 'utf8');
const data = JSON.parse(raw.replace(/^\uFEFF/, ''));

Error 9: Incorrectly Escaped Quotes

Double quotes inside a JSON string must be escaped with a backslash. A bare double quote inside a string value breaks the parser.

WRONG:

{"message": "She said "hello" to me"}

Error: Unexpected token s in JSON at position 18

FIXED:

{"message": "She said \"hello\" to me"}

Error 10: Special Characters and Control Characters

Newlines, tabs, and other control characters must be escaped inside JSON strings. Raw newlines within a string value are not valid.

WRONG (raw newline in string):

{"message": "line one
line two"}

Error: Unexpected token \n in JSON at position 22

FIXED (use \n escape):

{"message": "line one\nline two"}

3. How to Debug JSON Parse Errors

When you encounter a JSON parse error, these tools and techniques will help you find the exact problem.

Browser Console (Chrome/Firefox/Edge)

Paste your JSON into the browser console to get the exact error position:

// Paste this in your browser console:
try {
  JSON.parse('{"name": "Alice",}');
} catch (e) {
  console.error(e.message);
  // → "Expected double-quoted property name in JSON at position 17"
}

Tip: Chrome DevTools shows the exact position number. Count characters from the beginning to find the bad character.

Node.js

Use a try/catch block to get detailed error information:

const fs = require('fs');

try {
  const raw = fs.readFileSync('config.json', 'utf8');
  const data = JSON.parse(raw);
} catch (err) {
  console.error('JSON parse failed:', err.message);
  // Shows: "Unexpected token , in JSON at position 42"

  // Extract the position and show surrounding context
  const pos = err.message.match(/position (\d+)/);
  if (pos) {
    const p = parseInt(pos[1]);
    const raw = fs.readFileSync('config.json', 'utf8');
    console.error('Context:', raw.substring(p - 20, p + 20));
    console.error('         ' + ' '.repeat(20) + '^');
  }
}

Python (json.loads)

Python provides the most helpful error messages, including line and column numbers:

import json

raw = """{"name": "Alice", "age": 30,}"""

try:
    data = json.loads(raw)
except json.JSONDecodeError as e:
    print(f"Error: {e.msg}")
    print(f"Line: {e.lineno}, Column: {e.colno}")
    print(f"Character position: {e.pos}")
    # Output:
    # Error: Expecting property name enclosed in double quotes
    # Line: 1, Column: 29
    # Character position: 28

jq (Command-Line)

jq is a powerful command-line JSON processor. Feed it invalid JSON and it will tell you exactly where the problem is:

# Validate a JSON file
$ jq . config.json
# If valid: pretty-printed output
# If invalid: parse error at line X, column Y

# Validate inline JSON
$ echo '{"name": "Alice",}' | jq .
# parse error (Invalid numeric literal) at line 1, column 19

Tip: If your JSON is in a variable or comes from an API, pipe it directly to jq:

# Validate JSON from an API response
$ curl -s https://api.example.com/data | jq .

# Validate JSON from a shell variable
$ echo "$MY_JSON_VAR" | jq .

4. JSON Validators: Tools to Catch Errors Before They Hit Production

Prevention is better than debugging. Use these validators in your workflow.

Online Validators

Paste your JSON and get instant feedback with highlighted errors:

  • DevToolBox JSON Formatter — Our built-in tool validates, formats, and highlights JSON errors in real time.
  • JSONLint.com — The classic online JSON validator.
  • JSON Editor Online — Tree view with error highlighting.

VS Code Built-in Validation

VS Code automatically validates .json files and shows errors with red squiggly lines. No extension needed. For files that use JSON with comments (like tsconfig.json), VS Code uses the JSONC parser automatically.

Tip: Use the "Format Document" command (Shift+Alt+F) to auto-format JSON. If formatting fails, your JSON has a syntax error.

Command-Line Validators

Validate JSON in your terminal or CI pipeline:

# jq — validate and pretty-print
$ jq . data.json

# Python built-in
$ python -m json.tool data.json

# Node.js one-liner
$ node -e "JSON.parse(require('fs').readFileSync('data.json','utf8'))"

# Validate multiple files in a directory
$ for f in *.json; do echo -n "$f: "; jq . "$f" > /dev/null 2>&1 && echo "OK" || echo "INVALID"; done

jq . — Validates and pretty-prints. Exit code 0 means valid.

python -m json.tool — Built into Python, no installation needed.

node -e — Quick validation using Node.js.

5. Fixing JSON from APIs: Handling Edge Cases

APIs sometimes return data that is not valid JSON. Here are common scenarios and fixes.

API Returns HTML Instead of JSON

If the server returns an HTML error page (404, 500) instead of JSON, JSON.parse() fails on the first < character.

Fix: Check the Content-Type header and response status before parsing:

async function fetchJSON(url) {
  const response = await fetch(url);

  // Check status first
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  // Check Content-Type header
  const contentType = response.headers.get('content-type');
  if (!contentType || !contentType.includes('application/json')) {
    const text = await response.text();
    throw new Error(
      `Expected JSON but got ${contentType}: ${text.substring(0, 100)}...`
    );
  }

  return response.json();
}

JSONP Wrapped Response

Some legacy APIs wrap JSON in a function call (callback({...})). Strip the wrapper before parsing:

// JSONP response: callback({"name": "Alice", "age": 30})
function parseJSONP(jsonpString) {
  // Strip the function wrapper
  const match = jsonpString.match(/^[a-zA-Z_][a-zA-Z0-9_]*\((.*)\);?$/s);
  if (match) {
    return JSON.parse(match[1]);
  }
  // If no wrapper found, try parsing as regular JSON
  return JSON.parse(jsonpString);
}

Concatenated JSON / NDJSON

Some APIs stream multiple JSON objects separated by newlines (NDJSON / JSON Lines). Parse each line separately:

// NDJSON: one JSON object per line
const ndjson = `{"id":1,"name":"Alice"}
{"id":2,"name":"Bob"}
{"id":3,"name":"Charlie"}`;

const objects = ndjson
  .split('\n')
  .filter(line => line.trim())
  .map(line => JSON.parse(line));

console.log(objects);
// [{id:1,name:"Alice"}, {id:2,name:"Bob"}, {id:3,name:"Charlie"}]

Truncated JSON Response

Network timeouts or response size limits can truncate JSON mid-stream, resulting in invalid JSON. Always validate before parsing:

function safeJSONParse(text) {
  try {
    return { data: JSON.parse(text), error: null };
  } catch (err) {
    return {
      data: null,
      error: {
        message: err.message,
        position: err.message.match(/position (\d+)/)?.[1],
        preview: text.substring(0, 200) + (text.length > 200 ? '...' : ''),
      }
    };
  }
}

// Usage
const result = safeJSONParse(apiResponse);
if (result.error) {
  console.error('Invalid JSON:', result.error.message);
  console.error('First 200 chars:', result.error.preview);
}

6. JSON5 and JSONC: When to Use Relaxed Formats

Sometimes strict JSON is too painful for configuration files. Two popular alternatives exist:

JSONC (JSON with Comments)

JSONC allows // and /* */ comments in JSON. It is used by VS Code settings, tsconfig.json, and other developer tools.

JSONC Example:

{
  // Database configuration
  "host": "localhost",
  "port": 5432,

  /* Credentials — loaded from env in production */
  "username": "dev_user",
  "password": "dev_pass",

  // Enable query logging in development
  "logging": true
}

Parsing JSONC in Node.js:

// Using the 'jsonc-parser' package (used by VS Code internally)
const { parse } = require('jsonc-parser');

const jsoncString = fs.readFileSync('config.jsonc', 'utf8');
const config = parse(jsoncString);

// Or strip comments manually with a regex (simplified, not production-ready)
function stripJsonComments(str) {
  return str
    .replace(/\/\/.*$/gm, '')          // Remove single-line comments
    .replace(/\/\*[\s\S]*?\*\//g, '');  // Remove multi-line comments
}

JSON5

JSON5 is a superset of JSON that allows: single quotes, unquoted keys, trailing commas, comments, multiline strings, hexadecimal numbers, and more.

JSON5 Example:

{
  // JSON5 allows all of this:
  unquotedKey: 'single quotes are fine',
  trailingComma: true,
  hexValue: 0xFF,
  leadingDot: .5,
  multiline: 'line one \
line two',
  infinity: Infinity,
  nan: NaN,
}

Parsing JSON5 in Node.js:

// npm install json5
const JSON5 = require('json5');

const config = JSON5.parse(fs.readFileSync('config.json5', 'utf8'));

// JSON5 can also stringify
const str = JSON5.stringify(config, null, 2);

When to Use Each Format

FormatUse WhenDo NOT Use When
JSONAPI communication, data exchange, any machine-to-machine formatConfig files that humans edit frequently
JSONCConfig files (tsconfig.json, VS Code settings)API responses or data interchange
JSON5Human-written config files where DX matters mostAPI responses or when standard JSON parsers are required

7. Frequently Asked Questions

Why does JSON.parse() fail on valid JavaScript objects?

Because JSON is NOT JavaScript. JSON requires double-quoted keys and strings, does not allow trailing commas, does not support comments, undefined, functions, or any JavaScript-specific syntax. Use JSON.stringify(obj) to convert a JavaScript object to valid JSON.

How do I find the exact position of a JSON error?

Most parsers include the character position in the error message (e.g., "at position 42"). In VS Code, use Ctrl+G to jump to a line number, and count characters on that line. Online validators like JSONLint highlight the exact error location visually. Python's json module gives you both line and column numbers.

Can I use single quotes in JSON?

No. The JSON specification (RFC 8259) requires double quotes for all strings and property names. Single quotes are not valid JSON. If you need single-quote support, use JSON5 which allows both single and double quotes.

Why does my JSON file work in VS Code but fail in my application?

VS Code uses a JSONC parser (JSON with Comments) for many file types like tsconfig.json and .vscode/settings.json. Your application likely uses a strict JSON parser. Remove all comments and trailing commas to make it strict-JSON-compatible, or use a JSONC/JSON5 parser in your application.

How do I handle JSON with a BOM character?

Strip the BOM before parsing. In JavaScript: jsonString.replace(/^\uFEFF/, ''). In Node.js, read the file with UTF-8 encoding and strip the BOM: fs.readFileSync(path, 'utf8').replace(/^\uFEFF/, ''). Most modern editors can be configured to save files without BOM.

𝕏 Twitterin LinkedIn
Var detta hjälpsamt?

Håll dig uppdaterad

Få veckovisa dev-tips och nya verktyg.

Ingen spam. Avsluta när som helst.

Try These Related Tools

{ }JSON FormatterY{}JSON ↔ YAML Converter\Escape / UnescapeJSON Validator

Related Articles

JSON vs YAML vs TOML: Vilket konfigformat ska du använda?

Jämför konfigurationsformaten JSON, YAML och TOML.

JSON Formatter & Validator: Formatera och Validera JSON Online

Gratis online JSON-formaterare och validator. Formatera JSON, hitta syntaxfel med kodexempel i JavaScript och Python.

JSON Schema Validering: Typer, verktyg och bästa praxis

Allt om JSON Schema-validering: från grundläggande typer till avancerade mönster, valideringsbibliotek och integration med TypeScript och API:er.