leogoesger
leogoesger

Reputation: 3820

JSON::ParserError: 743: unexpected token in ROR

I am getting this error when try to parse the response from rest_client.

JSON::ParserError: 743: unexpected token at '{

require 'rest_client'
require 'json'

class Kele
    attr_accessor :data
    def initialize(u,p)
        #@values = {email: u, password: p}
        @values = '{"email": "[email protected]", "password": "password"}'
        @headers = {:content_type => 'application/json'}
        @data = self.post
    end

    def post
        response = RestClient.post 'https://private-anon-8506c5665f-blocapi.apiary-mock.com/api/v1/sessions', @values, @headers
    end
end

In Ruby irb,

 r = b.post
=> <RestClient::Response 200 "{\n    \"auth...">

 JSON.parse(r.body)
=> JSON::ParserError: 743: unexpected token at '{

a = Kele.new(1,2)
=> #<Kele:0x000000042e2e18 @values="{\"email\": \"[email protected]\", \"password\": \"password\"}", @headers={:content_type=>"application/json"}, @data=<RestClient::Response 200 "{\n    \"auth...">>

 a.post.body
 => "{\n    \"auth_token\":\"eyJ0eXAiOiJKV1QiLCJhhGciOiJIUzI1NiJ9.eyJhcGlfa2V5IjoiYTc2MDZkNTBhYjA3NDE4ZWE4ZmU5NzliY2YxNTM1ZjAiLCJ1c2VyX2lkIjoyMzAzMTExLCJuYW1lIjoiQmVuIE5lZWx5In0.3VXD-FxOoxaGXHu6vmL8g191bl5F_oKe9qj8Khmp9F0\",\n    \"user\":\n        {\n            \"id\":2307245,\n            \"email:\"[email protected]\",\n            \"created_at\":\"2015-08-11T16:31:08.836-07:00\",\n            \"updated_at\":\"2015-11-04T13:13:32.457-08:00\",\n            \"facebook_id\":null,\n            ...,\n            \"gender\":null\n        }\n}"

I tried this using HTTParty as well:

require 'HTTParty'
class Kele
    include HTTParty
    def initialize(email,password)
        @options = {query: {email: email, password: password}}
    end

    def post
        self.class.post('https://private-anon-8506c5665f-blocapi.apiary-mock.com/api/v1/sessions', @options)
    end
end

I still get this error:

 JSON.parse(a.post.body)
=> JSON::ParserError: 743: unexpected token at '{

Upvotes: 4

Views: 8496

Answers (2)

leogoesger
leogoesger

Reputation: 3820

I am not sure every case of error 743 from JSON is the same, but in my case is caused by the API endpoint. It was slightly different than the one I suppose to use.

So, I would check on your API endpoint URL first if you get this error, and make sure you are using the correct one.

In this case,

I should be using https://www.bloc.io/api/v1/sessions

Upvotes: 0

Glyoko
Glyoko

Reputation: 2090

In your second example, r is not JSON, it is a RestClient::Response object and cannot be parsed. You need to parse the r.body of the RestClient::Response, as you referenced it with a.post.body in your second example.

r = b.post         # => <RestClient::Response 200 "{\n    \"auth...">
JSON.parse(r)      # => JSON::ParserError: ...
r.body             # => "Some valid JSON string"
JSON.parse(r.body) # => Parses "Some valid JSON string"

Upvotes: 2

Related Questions