Reputation: 5872
I am receiving a JSON string from a Rails controller and passing it to a worker; however, when it gets to the worker, it's converted to a string, which I am then trying to convert back to JSON. When I do this, I am receiving errors.
Below is an example of what I'm trying to do, along with the error received when trying to do so:
[18] pry(#<SampleWorker>)> str = '{"id"=>"F02DD5GH77X", "created"=>1630584313, "timestamp"=>1630584313}'
=> "{\"id\"=>\"F02DD5GH77X\", \"created\"=>1630584313, \"timestamp\"=>1630584313}"
[19] pry(#<SampleWorker>)> JSON.parse(str)
JSON::ParserError: 809: unexpected token at '{"id"=>"F02DD5GH77X", "created"=>1630584313, "timestamp"=>1630584313}'
from /usr/local/lib/ruby/3.0.0/json/common.rb:216:in `parse'
[20] pry(#<SampleWorker>)> JSON(str)
JSON::ParserError: 809: unexpected token at '{"id"=>"F02DD5GH77X", "created"=>1630584313, "timestamp"=>1630584313}'
from /usr/local/lib/ruby/3.0.0/json/common.rb:216:in `parse'
[21] pry(#<SampleWorker>)>
I've even tried to replace the \"
and that doesn't seem to help:
[26] pry(#<SampleWorker>)> str.gsub("\"", "'")
=> "{'id'=>'F02DD5GH77X', 'created'=>1630584313, 'timestamp'=>1630584313}"
[27] pry(#<SampleWorker>)> JSON.parse(str.gsub("\"", "'"))
JSON::ParserError: 809: unexpected token at '{'id'=>'F02DD5GH77X', 'created'=>1630584313, 'timestamp'=>1630584313}'
from /usr/local/lib/ruby/3.0.0/json/common.rb:216:in `parse'
[28] pry(#<SampleWorker>)>
Upvotes: 0
Views: 366
Reputation: 14890
You need to replace =>
with :
str = str.gsub("=>", ":")
# => "{\"id\":\"F02DD5GH77X\", \"created\":1630584313, \"timestamp\":1630584313}"
JSON.parse(str)
# => {"id"=>"F02DD5GH77X", "created"=>1630584313, "timestamp"=>1630584313}
Upvotes: 1