JSON::ParserError
RubyERRORNotableParsing

Invalid JSON input

Quick Answer

Always rescue JSON::ParserError when parsing untrusted or external input; validate the response content-type before parsing.

What this means

Raised by JSON.parse when the input string is not valid JSON. A subclass of JSON::JSONError and StandardError. Common when parsing API responses, config files, or user input that may be malformed.

Why it happens
  1. 1Trailing commas, unquoted keys, or JavaScript-style comments in the input
  2. 2Parsing an HTML error page that was returned instead of JSON
  3. 3Truncated network response

Fix

Rescue JSON::ParserError with fallback

Rescue JSON::ParserError with fallback
require 'json'

def safe_parse(str, fallback = {})
  JSON.parse(str)
rescue JSON::ParserError => e
  Rails.logger.warn("JSON parse failed: #{e.message}")
  fallback
end

Why this works

Rescuing with a fallback prevents a bad payload from crashing the caller while logging the problem for inspection.

Code examples
Reproducing the errorruby
JSON.parse('{bad json}')
# JSON::ParserError: 767: unexpected token at '{bad json}'
Rescue in HTTP clientruby
body = response.body
begin
  data = JSON.parse(body)
rescue JSON::ParserError
  raise "Non-JSON response: #{body[0, 200]}"
end
JSON.parse with symbolized keysruby
data = JSON.parse(json_str, symbolize_names: true)
# Raises JSON::ParserError if invalid
Sources
Official documentation ↗

Ruby Standard Library Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors