0

In my rails database I have an object with a text field that is valid json:

"\"AACAY, AAOI, AAON, AATI, ABAX,ZYXI\""

If I call JSON.parse on the field in ruby it errors with this:

JSON::ParserError: 784: unexpected token at '"AACAY, AAOI, AAON, AATI, ABAX,ZYXI"'

However, if I call JSON.parse on the same string in the browser it works.

Why is the ruby call failing?

4
  • 1
    Doesn't JSON.parse expect JSON, not a JSON fragment? Commented Feb 8, 2017 at 22:01
  • I think you're right. I assumed incorrectly they did similar things. Commented Feb 8, 2017 at 22:13
  • This works find on my end. You may want to update your json gem and try it out in pry or irb. I have tried out your string it passed correctly. I am using ruby 2.3.1 Commented Feb 8, 2017 at 22:17
  • JSON.parse(string) and JSON.load(string) both work for me Commented Feb 8, 2017 at 22:19

3 Answers 3

2

I encounter the same issue with JSON.parse for a string nested in a JSON string. My solution was to escape JSON::ParserError with YAML.

YAML.load("\"AACAY, AAOI, AAON, AATI, ABAX,ZYXI\"")
=> "AACAY, AAOI, AAON, AATI, ABAX,ZYXI"

Beware of gotchas though. See this SO thread

Sign up to request clarification or add additional context in comments.

Comments

1

Its a bug in the JSON parser that is fixed as of v2.0 of the json gem.

# json_parser_test.rb
require 'json'
puts JSON.parse("\"AACAY, AAOI, AAON, AATI, ABAX,ZYXI\"")

maxcal@MaxBook ~/p/s/tmp> gem list json

*** LOCAL GEMS ***

json (1.8.3)
json-schema (2.7.0)
jsonapi (0.1.1.beta6)
jsonapi-parser (0.1.1.beta3)
jsonapi-renderer (0.1.1.beta1)
multi_json (1.12.1, 1.11.2)
maxcal@MaxBook ~/p/s/tmp> ruby json_parser_test.rb 
/Users/maxcal/.rbenv/versions/2.3.1/lib/ruby/2.3.0/json/common.rb:156:in `parse': 784: unexpected token at '"AACAY, AAOI, AAON, AATI, ABAX,ZYXI"' (JSON::ParserError)
    from /Users/maxcal/.rbenv/versions/2.3.1/lib/ruby/2.3.0/json/common.rb:156:in `parse'
    from json_parser_test.rb:2:in `<main>'

Upgrading the JSON gem makes the parser error disappear:

maxcal@MaxBook ~/p/s/tmp> gem install json -v 2.0
Fetching: json-2.0.0.gem (100%)
Building native extensions.  This could take a while...
Successfully installed json-2.0.0
Building YARD (yri) index for json-2.0.0...
Done installing documentation for json after 2 seconds
1 gem installed
maxcal@MaxBook ~/p/s/tmp> ruby json_parser_test.rb 
AACAY, AAOI, AAON, AATI, ABAX,ZYXI

Comments

0

JSON.parse() does not work with all string formats. String needs to have following format. "{\"AACAY\":\"AAOI\", \"AAON\":\"AATI\", \"ABAX\":\"ZYXI\"}" which contains stringified object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.