I am using Ruby on Rails 3 and I would like to solve an issue with the following code where a web client application receive back some JSON data from a web service application that uses a Rack middleware in order to respond.
我正在使用Ruby on Rails 3,我想解决以下代码的问题,其中Web客户端应用程序从使用Rack中间件的Web服务应用程序接收一些JSON数据以便响应。
In the web client app model I have
在我有的Web客户端应用程序模型中
response_parsed = JSON.parse(response.body)
if response_parsed["account"]
...
else
return response
end
In the above code the response.body
come back from the web service app that uses a Rack middleware to respond to the web client:
在上面的代码中,response.body从Web服务应用程序返回,该应用程序使用Rack中间件来响应Web客户端:
accounts = Account.where(:id => ids)
[200, {'Content-Type' => 'application/json'}, accounts.to_json] # That is, response.body = accounts.to_json
Data transmission is ok, but I get the following error
数据传输没问题,但是我收到以下错误
TypeError
can't convert String into Integer
*Application Trace*
lib/accounts.rb:107:in `[]'
The line 107
corresponds to
线107对应于
if response_parsed["account"]
...
Where and what is the problem? How to solve that?
哪里有什么问题?怎么解决?
If I try to debug the respons.body
I get
如果我尝试调试Respons.body我得到
# Note: this is an array!
"[{\"account\":{\"firstname\":\"Semio\",\"lastname\":\"Iaven\"\"}}]"
1 个解决方案
#1
3
If I'm saying something you already realize, forgive me.
如果我说的话你已经意识到了,请原谅我。
It looks like your response is a one-element array with a hash in it as the first element. Because the response is an array, when you use the [] it is expecting a integer representing the index of the item in the array you'd like to access, and that is what the error message means--it expected that you'd tell it the integer value of the item you wanted, but instead you gave it a string.
看起来你的响应是一个单元素数组,其中有一个哈希作为第一个元素。因为响应是一个数组,当你使用[]时,它需要一个整数来表示你想要访问的数组中项目的索引,这就是错误信息的含义 - 它预计你会告诉它你想要的项目的整数值,但你给它一个字符串。
If you instead do:
如果您改为:
response_parsed[0]['account']
It seems like you'd get what you want.
看起来你得到了你想要的东西。
#1
3
If I'm saying something you already realize, forgive me.
如果我说的话你已经意识到了,请原谅我。
It looks like your response is a one-element array with a hash in it as the first element. Because the response is an array, when you use the [] it is expecting a integer representing the index of the item in the array you'd like to access, and that is what the error message means--it expected that you'd tell it the integer value of the item you wanted, but instead you gave it a string.
看起来你的响应是一个单元素数组,其中有一个哈希作为第一个元素。因为响应是一个数组,当你使用[]时,它需要一个整数来表示你想要访问的数组中项目的索引,这就是错误信息的含义 - 它预计你会告诉它你想要的项目的整数值,但你给它一个字符串。
If you instead do:
如果您改为:
response_parsed[0]['account']
It seems like you'd get what you want.
看起来你得到了你想要的东西。