【问题标题】:JSON::ParserError 757 Unexpected tokenJSON::ParserError 757 意外令牌
【发布时间】:2015-08-19 15:25:55
【问题描述】:

关于我正在从事的工作的一些背景知识。我正在尝试创建一个应用程序来增加我的编码组合,但我无法让这个应用程序与我一起工作。我遵循了其中的一部分指南,特别是将 Steam OpenID/Omniuath 与 Ruby on Rails 集成,因为它使用没有 CSRF 令牌的 POST....yadda yadda yadda。 Anyhoo,到目前为止,我试图做到这一点是在通过 Steam 登录时,就在这一刻,将显示玩家拥有的游戏列表。但是它不适合我。我的控制器代码如下。

    class WelcomeController < ApplicationController
  skip_before_filter :verify_authenticity_token, :only => :auth_callback
  def index
    @gameslibrary = []
    if session.key? :current_user
    url = URI.parse("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=#{ENV['STEAM_WEB_API_KEY']}&account_id=#{session[:current_user][:uid]}")
    res = Net::HTTP::get(url)
    @gameslibrary = JSON.parse(res)['game_count']['app_id']['name']['playtime_forever'] || []
  end
end
  def auth_callback
      auth = request.env['omniauth.auth']
      session[:current_user] = { :nickname => auth.info['nickname'],
                                            :image => auth.info['image'],
                                            :uid => auth.uid }
      redirect_to root_url
    end
end

这是我的视图代码

<h1>Welcome#index</h1>
<%= link_to image_tag("http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_large_noborder.png"), '/auth/steam' %>
<% if session.key? :current_user %>
<h3>Current User:</h3>
<%= image_tag session[:current_user][:image] %>
<p><%= session[:current_user][:nickname] %></p>
<p><%= session[:current_user][:uid] %> </p>
<% end %>
<ul>
  <% @gameslibrary.each do |game| %>
  <li><%= puts game %></li>
  <% end %>
</ul>

我的 JSON 解析返回以下内容

757: unexpected token at '<html> <head> <title>500 Internal Server Error</title> </head> <body> <h1>Internal Server Error</h1> </body> </html>'

现在 Steam Web API 确实支持 JSON 输出。 JSON解析后的那些项目是数组/数组中的项目的实际名称。我在这里做错了什么?为了获得更多帮助,我将如何将 JSON 解析数据从数组转换为哈希? (或者那是自动的吗?)我对大部分都是新手,这是我自己完成的第一个应用程序。如果有人想看的话,我正在使用 Steam Web API 中的 GetOwnedGamesv0001。

【问题讨论】:

  • 请发布Net::HTTP::get(url)的输出。

标签: ruby-on-rails ruby json steam


【解决方案1】:

问题肯定是响应,这是一个无效的 JSON,你可以做什么首先将此代码移动到模型,然后检查你从尝试发送请求的 url 获得的响应代码,如果它不同于 200不要尝试 JSON.parse 响应,因为你会得到你现在得到的错误。

做一些类似的事情:

url =      URI.parse("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=#{ENV['STEAM_WEB_API_KEY']}&account_id=#{session[:current_user][:uid]}")

if Net::HTTP.get_response(url).kind_of? Net::HTTPSuccess
  @gameslibrary = JSON.parse(Net::HTTP::get(url))['game_count']['app_id']['name']['playtime_forever'] || []
else
  ... raise or log or something ...
end

【讨论】:

    猜你喜欢
    • 2017-04-03
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 2021-03-05
    • 2014-10-06
    相关资源
    最近更新 更多