jsonruby-on-railsrubyjsonparser

How to parse json string data having symbols as key instead of string in Ruby?


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)

Solution

  • 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.