How to Parse JSON Safely (and Fix "Unexpected token < in JSON at position 0")
Parse JSON in Python, JavaScript, Java and Go with proper error handling, and diagnose the classic errors — Unexpected token '<', Unexpected end of JSON input and Expecting value — in minutes.
By Software Side Hustles Editorial Team · Published · Updated · 5 min read
Quick answer: "Unexpected token <" means you tried to parse HTML as JSON — usually an error page, a login redirect or a 404 returned by the server. "Unexpected end of JSON input" (JavaScript) and "Expecting value: line 1 column 1" (Python) usually mean the body was empty. Log the raw response body and status code before parsing, and the cause is normally obvious.
What the common JSON errors mean
| Error message | Language | Usual cause |
|---|---|---|
Unexpected token '<', "<!DOCTYPE "... is not valid JSON | JavaScript | Server returned an HTML page |
Unexpected token < in JSON at position 0 | JavaScript (older engines) | Same as above |
Unexpected end of JSON input | JavaScript | Empty body (204, failed request, empty file) |
"undefined" is not valid JSON | JavaScript | You passed undefined to JSON.parse |
Expecting value: line 1 column 1 (char 0) | Python | Empty body or HTML |
Expecting property name enclosed in double quotes | Python | Single quotes (or, in older Python versions, a trailing comma) |
invalid character '<' looking for beginning of value | Go | HTML instead of JSON |
Unrecognized token / JsonParseException | Java (Jackson) | Non-JSON input |
How do I fix "Unexpected token < in JSON at position 0"?
The first character of the response was < — the start of <!DOCTYPE html> or <html>. Typical causes:
- Wrong URL. A typo or missing
/apiprefix hits your front-end's catch-all route, which servesindex.html. Single-page apps with dev servers do this constantly. - An error page. The server crashed and returned a 500 HTML page, or a proxy returned 502/504.
- Authentication. Your session expired and the server redirected the request to a login page.
- A local file path. In a bundler,
fetch("data.json")resolved relative to the current page, not where you expected.
Inspect before you parse:
const res = await fetch("/api/users");const text = await res.text();console.log(res.status, res.headers.get("content-type"), text.slice(0, 200));Then make the production code defensive:
async function getJson(url) { const res = await fetch(url); if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`); const type = res.headers.get("content-type") ?? ""; if (!type.includes("application/json")) { throw new Error(`Expected JSON from ${url}, got ${type || "no content type"}`); } return res.json();}This turns a confusing parse error into a message that tells you exactly what went wrong. Remember that fetch does not reject on 404 or 500 — only on network failure — so the res.ok check is essential.
How do I fix "Unexpected end of JSON input"?
The string was empty or cut off. Common causes: calling res.json() on a 204 No Content response, reading a file that is still being written, or a request that was aborted. Check res.status === 204 or text.length === 0 before parsing, and decide what an empty body should mean in your code.
How do I parse JSON in Python?
import json
data = json.loads('{"name": "Ada", "age": 36}') # str -> dictwith open("config.json", encoding="utf-8") as f: config = json.load(f) # file -> dict
try: payload = json.loads(raw)except json.JSONDecodeError as e: print(f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}") print(raw[:200])JSONDecodeError is a subclass of ValueError, so existing except ValueError blocks catch it too. With the requests library, check r.status_code (or call r.raise_for_status()) before r.json().
Python-specific gotchas: JSON requires double quotes, so a string produced by str(my_dict) — {'a': 1} — is not JSON. Use json.dumps(my_dict) to produce JSON, and never use eval() to "parse" it.
How do I parse JSON in Java and Go?
Java (Jackson):
ObjectMapper mapper = new ObjectMapper();record User(String name, int age) {}User u = mapper.readValue(json, User.class);Jackson throws UnrecognizedPropertyException if the JSON contains fields your class does not have. Either annotate the class with @JsonIgnoreProperties(ignoreUnknown = true) or configure mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) — whichever matches how strict your API contract should be.
Go:
type User struct { Name string `json:"name"` Age int `json:"age"`}var u Userif err := json.Unmarshal(body, &u); err != nil { return fmt.Errorf("decode user: %w", err)}The Go gotcha: only exported (capitalised) struct fields are filled. A field named name stays empty with no error.
Silent JSON problems that do not throw
Some of the worst JSON bugs produce no error at all:
- Large integers lose precision in JavaScript.
JSON.parse('{"id": 9007199254740993}').idis9007199254740992. IDs beyond 2^53 should travel as strings. - Dates are just strings.
JSON.parsegives you"2026-10-26T09:00:00Z", not aDate. Convert explicitly — see dates, times and time zones. - Missing fields become
undefinedin JavaScript and default values in Go and Java. Validate the shape with a schema library (Zod, Pydantic, JSON Schema) at the boundary. - Trailing commas and comments are not valid JSON, even though many config files (
tsconfig.json) allow them through a lenient parser.
Frequently asked questions
How do I check if a string is valid JSON?
Try to parse it and catch the error. There is no reliable regex for JSON.
Why does JSON.parse fail on single quotes?
The JSON specification only allows double-quoted strings and property names. {'a': 1} is valid JavaScript but invalid JSON.
How do I pretty-print JSON?
JSON.stringify(obj, null, 2) in JavaScript, json.dumps(obj, indent=2) in Python, python -m json.tool file.json or jq . on the command line.
Why does my fetch work in the browser address bar but fail in code?
Different headers, cookies or origin. If the console also mentions CORS, read how to fix CORS errors.
Where this skill pays off
Debugging from an error message to a root cause — and explaining it so the next person does not repeat it — is one of the most valued skills in AI code-evaluation work, where you judge whether a model's fix actually addresses the cause. See how developers earn money training AI models.