0

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>)> 
1
  • You're not getting JSON back from SampleWorker. You're getting the output of Hash#to_s. { "foo" => 'bar' }.to_s gives "{\"foo\"=>\"bar\"}". Is SampleWorker under your control? Commented Sep 2, 2021 at 12:27

1 Answer 1

1

You need to replace => with :

str = str.gsub("=>", ":")
# => "{\"id\":\"F02DD5GH77X\", \"created\":1630584313, \"timestamp\":1630584313}"

JSON.parse(str)
# => {"id"=>"F02DD5GH77X", "created"=>1630584313, "timestamp"=>1630584313}

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.