Read more

How to fix: "unexpected token" error for JSON.parse

Arne Hartherz
April 15, 2013Software engineer at makandra GmbH

When using the json gem Show archive.org snapshot , you might run into this error when using JSON.parse:

>> json = 'foo'.to_json
>> JSON.parse(json)
JSON::ParserError: 757: unexpected token at '"foo"'
	from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
	from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
	from (irb):1

Why?

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

The error above happens because the JSON you supplied is invalid.

While to_json does work correctly, the result itself is not JSON that can be parsed back, as that string element is not inside an object like a hash (i.e. JSONObject) or array.

How to fix it

So, in order to fix that, use a valid object to build JSON from, e.g. an array:

>> JSON.parse([ 'foo' ].to_json).first
=> "foo"

When you do that, remember to select the record from the array after parsing (e.g. via first).

How to work around the problem

If you can't control the input, you may use the quirks_mode option to work around the issue:

>> json = 'foo'.to_json
>> JSON.parse(json, :quirks_mode => true)
=> "foo"

Prefer using to_json on objects that can be parsed back over this workaround.

Posted by Arne Hartherz to makandra dev (2013-04-15 14:18)