JSON Errors / Ruby

JSON::ParserError: unexpected token at ...

How to Fix: JSON::ParserError: unexpected token at ...

JSON.parse could not read the input as JSON. The message quotes the text near the failure - "unexpected token at '<html>...'" - so the quoted snippet is your first clue about what actually arrived.

A related trap: JSON.parse(nil) raises TypeError, not ParserError, and an empty string raises "unexpected token at ''" - both usually mean an HTTP call returned no body.

{"find": "error"}paste your JSON below

Common causes

1. HTML or plain text instead of JSON

The quoted token starts with '<' - an error page or redirect came back. Check response.code before parsing.

2. Ruby hash syntax mistaken for JSON

A hash printed with puts/inspect uses => and symbols - that is Ruby literal syntax, not JSON.

Invalid
{:name=>"Ada", :age=>36}   # hash.inspect output, not JSON
Valid
{"name": "Ada", "age": 36}  # hash.to_json output

3. Single quotes or trailing commas

Hand-written pseudo-JSON: {'name': 'Ada'} or {"a": 1,} both raise ParserError, same as in every strict parser.

How to fix it

Guard the HTTP boundary (plain Ruby / Rails)
response = Net::HTTP.get_response(uri)
raise "HTTP #{response.code}: #{response.body[0, 200]}" unless response.is_a?(Net::HTTPSuccess)

body = response.body.to_s
data = body.strip.empty? ? nil : JSON.parse(body)
Serialize with to_json, never inspect/to_s
require "json"

hash = { name: "Ada", age: 36 }
hash.to_json      # => '{"name":"Ada","age":36}'  (valid JSON)
hash.to_s         # => '{:name=>"Ada", :age=>36}' (NOT JSON)
Symbolize keys when parsing
data = JSON.parse(body, symbolize_names: true)
data[:name]   # instead of data["name"]

Frequently asked questions

Why does JSON.parse(nil) raise TypeError instead of ParserError?

JSON.parse requires a string; nil fails the type check before parsing starts. Coerce and guard first: parse only when body.to_s.strip is non-empty, or rescue both TypeError and JSON::ParserError at boundaries.

How do I safely parse untrusted JSON in Rails?

Wrap in begin/rescue JSON::ParserError and return a 400 with a clear message. Do not use the quirky JSON.parse(json, quirks_mode: true) to accept broken input - fix the producer instead.

What is the difference between JSON.parse and JSON.load?

JSON.load can invoke custom class deserialization (json_create) and historically had unsafe defaults with untrusted input. Always use JSON.parse for data you did not produce yourself.

Last updated:

Related JSON errors

You might also need

Free and in-browser, like everything on JSON Console. Browse all tools →