JSON::ParserError: 743: unexpected token in ROR

JSON::ParserError: 743: unexpected token in ROR

我在尝试解析来自 rest_client 的响应时收到此错误。

JSON::ParserError: 743: '{

处的意外标记
require 'rest_client'
require 'json'

class Kele
    attr_accessor :data
    def initialize(u,p)
        #@values = {email: u, password: p}
        @values = '{"email": "antblessing@gmail.com", "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\": \"antblessing@gmail.com\", \"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:\"antblessing@gmail.com\",\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 '{

在您的第二个示例中,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"

我不确定来自 JSON 的错误 743 的每个案例都是相同的,但在我的案例中是由 API 端点引起的。它与我想使用的略有不同。

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

在这种情况下,

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