Reputation: 3
Here's the json string example
json = "{:status=>\"ok\", :hitcount=>\"1\", :request_date=>Wed, 10 Oct 2019 00:00:00 +0000}"
I have tried below mentioned snippet but this didn't work and gives error JSON::ParserError (765: unexpected token at
require 'json'
JSON.parse(json)
Upvotes: 0
Views: 168
Reputation: 5813
Unfortunately, JSON can't represent Ruby symbols. JSON also requires both keys and values to be quoted, so what you've provided isn't valid JSON and will break a JSON parser. You want just:
json = "{\"status\": \"ok\", \"hitcount\": \"1\", \"request_date\": \"Wed, 10 Oct 2019 00:00:00 +0000\"}"
And then the Ruby JSON parser (thanks @engineersmnky!) has a nifty feature:
JSON.parse(json, symbolize_names: true)
Upvotes: 0
Reputation: 162
You can use eval()
to turn this string into ruby code (a hash). You will get some issues because the date is not quoted. (I just asked ChatGPT to write the Regex for it). This will turn your string into a proper ruby hash:
json = "{:status=>\"ok\", :hitcount=>\"1\", :request_date=>Wed, 10 Oct 2019 00:00:00 +0000}"
fixed_string = json.gsub(/:request_date=>(\w+,\s\d+\s\w+\s\d+\s\d+:\d+:\d+\s\+\d+)/, ':request_date=>"\1"')
hash = eval(fixed_string)
Output:
{:status=>"ok", :hitcount=>"1", :request_date=>"Wed, 10 Oct 2019 00:00:00 +0000"}
Please note that using eval comes with security risks if you cannot control the input and the problem seems to be how your output is generated.
Upvotes: -1
Reputation: 1
It does look like a formatting issue. For example if you were to have an ordinary hash with the same data, and convert it to JSON it will look a bit different:
require 'json'
# Original value in post
# json = "{:status=>\"ok\", :hitcount=>\"1\", :request_date=>Wed, 10 Oct 2019 00:00:00 +0000}"
hash = {:status=>"ok", :hitcount=>"1", :request_date=>"Wed, 10 Oct 2019 00:00:00 +0000"}
json = hash.to_json
puts json # {"status":"ok","hitcount":"1","request_date":"Wed, 10 Oct 2019 00:00:00 +0000"}
parsed = JSON.parse(json)
puts parsed # {"status"=>"ok", "hitcount"=>"1", "request_date"=>"Wed, 10 Oct 2019 00:00:00 +0000"}
You can see what I mean here: https://onlinegdb.com/tr6JVAV6y
So I'd guess you'll need to see where that JSON is coming from and have it sent in a proper format.
Upvotes: 0