SoftwareSideHustles
Debugging

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 messageLanguageUsual cause
Unexpected token '<', "<!DOCTYPE "... is not valid JSONJavaScriptServer returned an HTML page
Unexpected token < in JSON at position 0JavaScript (older engines)Same as above
Unexpected end of JSON inputJavaScriptEmpty body (204, failed request, empty file)
"undefined" is not valid JSONJavaScriptYou passed undefined to JSON.parse
Expecting value: line 1 column 1 (char 0)PythonEmpty body or HTML
Expecting property name enclosed in double quotesPythonSingle quotes (or, in older Python versions, a trailing comma)
invalid character '<' looking for beginning of valueGoHTML instead of JSON
Unrecognized token / JsonParseExceptionJava (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:

  1. Wrong URL. A typo or missing /api prefix hits your front-end's catch-all route, which serves index.html. Single-page apps with dev servers do this constantly.
  2. An error page. The server crashed and returned a 500 HTML page, or a proxy returned 502/504.
  3. Authentication. Your session expired and the server redirected the request to a login page.
  4. A local file path. In a bundler, fetch("data.json") resolved relative to the current page, not where you expected.

Inspect before you parse:

javascript
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:

javascript
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?

python
import json
data = json.loads('{"name": "Ada", "age": 36}') # str -> dict
with 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):

java
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:

go
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
var u User
if 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}').id is 9007199254740992. IDs beyond 2^53 should travel as strings.
  • Dates are just strings. JSON.parse gives you "2026-10-26T09:00:00Z", not a Date. Convert explicitly — see dates, times and time zones.
  • Missing fields become undefined in 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.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy