2017-02-14 12 views
2

rest_clientからの応答を解析しようとすると、このエラーが発生します。JSON :: ParserError:743:RORの予期しないトークン

JSON :: ParserError:743:RubyのIRBで{

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 

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 

をIこのエラーが表示される:

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

答えて

1

2番目の例では、rはJSONではなく、RestClient :: Responseオブジェクトであり、解析できません。 2番目の例でa.post.bodyで参照したので、RestClient :: Responseのr.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

関連する問題