1

One of the fields in my table has the JSON type so inside the model to save string there I need to do something like:

create(modifications: string.to_json,
       ...
     )

to display this on the view the modifications column is parsed by JSON.parse which gives me the error 784: unexpected token at '"test registrant history"'

Long story short:

2.4.5 :042 > json_test = 'testing the string'.to_json
 => "\"testing the string\""
2.4.5 :043 > JSON.parse(json_test)
JSON::ParserError: 784: unexpected token at '"testing the string"'

why is this happening? how do you make JSON from a string then?

[Edit]

I'm on Rails 5 and Ruby 2.4.5

7
  • Rails 5, ruby 2.4.5 Commented Jan 14, 2022 at 13:41
  • @dbugger That's not true - without to_json it will be a simple string. I know json EOD is also string but formatting is different: "\"test note\"" vs "test note". There is one similarity - the error is the same for both after JSON.parse 784: unexpected token at Commented Jan 14, 2022 at 14:05
  • Hello @mr_muscle, Why do you use a JSON type for that field in your table? Can we have a sample of the data you expect onto that field? Commented Jan 14, 2022 at 15:46
  • JSON.parse("\"testing the string\"") works for me. Commented Jan 14, 2022 at 16:15
  • 1
    @SergioTulentsev it's working for recents versions of the json gem, but for older ones like 1.7.7 it's seems to throw that error. His version of rails seems to use an old version of the json gem Commented Jan 14, 2022 at 16:22

1 Answer 1

1

It's an issue on versions of json gem (<2). To avoid it you should use versions of json >2. So you might try to upgrade your rails version or just use quirks_mode: true.

JSON.parse(json_test, quirks_mode: true)

Here is a link to the issue on github json issue

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

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.