Skip to main content

Troubleshooting Common JSON Errors

Learning Focus

Most JSON bugs fall into a small number of known categories. This guide helps you identify the cause and apply the correct fix quickly.

Error Reference

Error MessageTypical CauseFix
Unexpected token 'Single-quoted string or keyReplace ' with "
Unexpected token }Trailing comma before } or ]Remove trailing comma
Unexpected end of JSON inputTruncated payloadValidate at both ends
SyntaxError: Unexpected token /Comment (//) in JSONRemove or use JSONC parser
Circular structureObject references itselfUse flatted or sanitize
Cannot serialize BigIntBigInt in JS object.toString() before stringify
JSONDecodeErrorPython — malformed inputtry/except json.JSONDecodeError
cannot marshal...Go — unexported field or unsupported typeExport fields; implement MarshalJSON

Validate First

# jq — exit 0 = valid
cat data.json | jq '.' > /dev/null && echo valid || echo INVALID

# Python
python3 -m json.tool data.json > /dev/null && echo valid

# Node.js
node -e "JSON.parse(require('fs').readFileSync('data.json','utf8'))" && echo valid

Single Quotes

// ✗ Invalid
{'name': 'Alice'}

// ✓ Valid
{"name": "Alice"}
Python Trap

str({'name': 'Alice'}) produces Python repr syntax — not JSON. Always use json.dumps().

Trailing Comma

// ✗ Invalid
{"a": 1, "b": 2,}
[1, 2, 3,]

// ✓ Valid
{"a": 1, "b": 2}
[1, 2, 3]

Circular References

// ⚠️ Throws TypeError: cyclic object value
const a = { name: "Alice" };
a.self = a;
JSON.stringify(a);

// Fix 1: custom replacer
JSON.stringify(a, (key, value) => key === 'self' ? undefined : value);

// Fix 2: flatted library
import { stringify } from 'flatted';
const safe = stringify(a);

Large Integer Precision

// ⚠️ Silent wrong result
JSON.parse('{"id": 9007199254740993}').id // 9007199254740992

// ✓ Keep as string
JSON.parse('{"id": "9007199254740993"}').id // "9007199254740993"

Deep Path Debugging with jq

# Step by step
echo '{"a":{"b":{"c":42}}}' | jq '.a'
echo '{"a":{"b":{"c":42}}}' | jq '.a.b'
echo '{"a":{"b":{"c":42}}}' | jq '.a.b.c'

# Discover all key paths
echo '{"a":1,"b":{"c":2}}' | jq 'paths(scalars)'

Quick Checklist

Before raising a bug, verify:

  • All keys and string values use double quotes
  • No trailing commas before } or ]
  • No comments in strict JSON context
  • No NaN, Infinity, or undefined
  • No circular object references
  • Large integers transmitted as strings
  • File encoding is UTF-8
  • NDJSON processed line by line, not as one document

Concept Map

Troubleshooting Decision Tree

  1. Parse Error? → Check: quotes (must be "), trailing commas, comments in JSON
  2. Serialization Error? → Check: circular references, BigInt, undefined values
  3. Data Integrity Issue? → Check: integer precision loss, file encoding (UTF-8), null vs missing key
  4. All else fails → Validate with jq '.' file.json or python3 -m json.tool file.json

What's Next