skip to Main Content

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)

3

Answers


  1. Follow this JSON syntax for starters: https://restfulapi.net/json-syntax/
    I believe your quotation marks inside your JSON are also causing an issue, you may have to escape them.

    Login or Signup to reply.
  2. 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_name: true)
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search