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
- 1Trailing commas, unquoted keys, or JavaScript-style comments in the input
- 2Parsing an HTML error page that was returned instead of JSON
- 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
endWhy 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]}"
endJSON.parse with symbolized keysruby
data = JSON.parse(json_str, symbolize_names: true) # Raises JSON::ParserError if invalid
Same error in other languages
Sources
Official documentation ↗
Ruby Standard Library Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev