2017-02-14 119 views
2

当尝试解析来自rest_client的响应时出现此错误。JSON :: ParserError:743:ROR中的意外令牌

JSON :: ParserError:743:在意外的标记“{

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 

在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}" 

这个我试过用HTTParty还有:

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 

我仍然得到这个错误:

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

回答

1

在第二个示例中,r不是JSON,它是一个RestClient :: Response对象,无法解析。您需要解析RestClient :: Response的r.body,正如您在第二个示例中使用a.post.body来引用它。

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" 
+0

谢谢,但我没有尝试,并抛出了同样的错误。我只是试图使用HTTParty,它也给出了相同的错误。 – Leogoesger

0

我不确定每个来自JSON的错误743的情况都是一样的,但在我的情况下是由API端点引起的。它与我想使用的稍有不同。

因此,如果出现此错误,我会首先检查您的API端点URL,并确保您使用的是正确的。

在这种情况下,

,我应该使用https://www.bloc.io/api/v1/sessions