Reputation: 29
JSON.parse returns back error:
# Ruby code in IRB
require 'json'
time_now = t.strftime("%a, %d %b %Y %H:%M:%S GMT")
hash = '"date":' + time_now.to_s
hash_json = JSON.parse(hash)
Error:
JSON::ParserError: 743: unexpected token at 'Sun, 14 May 2017 21:19:02 GMT'
My need is to have a JSON hash that has a Key/Value as:
# JSON hash
"date": "Sun, 14 May 2017 21:19:02 GMT"
Any insight ? I've tried this in a few ways, but running into same issue each time.
Upvotes: 0
Views: 585
Reputation: 475
You are not creating the hash correctly. This is incorrect:
hash = {'"date":' + time_now}
It should be:
hash = {'date' => time_now}
Upvotes: 0
Reputation: 29
Json parsing when you can use , data contain json structure ; so , hash = '"date":' + time_now.to_s problem here
hash = {"date"=> time_now.to_s}
Upvotes: -1
Reputation: 53
Your hash needs to be defined like this: hash = {"date" => time_now}
.
In addition, JSON.parse
returns a hash from a JSON formatted string. Hash has a method to_json
which does the opposite:
require 'json'
time_now = Time.now.strftime("%a, %d %b %Y %H:%M:%S GMT")
hash = {'date' => time_now}
hash_json = hash.to_json
Upvotes: 2