Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing valid JSON throwing errors

Tags:

json

ruby

I’m confused as to why this throws an error:

s = <<JSON
{"s": "This is \"valid\" JSON"}
JSON

JSON.parse(s) # => JSON::ParserError: 757: unexpected token at '{"s": "This is "valid" JSON"}'

Based on using http://jsonlint.com I can confirm that this is valid JSON, so what’s the deal? I get the feeling that I could be using %q{} here and things would be escaped properly, but I’d really rather use a heredoc here.

like image 334
Edward Ocampo-Gooding Avatar asked Dec 25 '22 10:12

Edward Ocampo-Gooding


1 Answers

It turns out that Ruby supports disabling interpolation in heredocs by surrounding the opening identifier with single quotes, so in my example above, it would look like this:

s = <<'JSON'
{"s": "This is \"valid\" JSON"}
JSON

JSON.parse(s) # => {"s"=>"This is \"valid\" JSON"}
like image 134
Edward Ocampo-Gooding Avatar answered Jan 09 '23 18:01

Edward Ocampo-Gooding