I am making an API call and receiving the following response:
{
"id": "http://www.google.com/",
"shares": 8262403,
"comments": 827
}
When I do:
api_call["shares"]
It just returns
shares
...and I want the value of "shares" so I have the share count. What am I missing?
You need to use JSON
:
require 'json'
str = '{
"id": "http://www.google.com/",
"shares": 8262403,
"comments": 827
}'
JSON.parse(str)['shares'] # => 8262403
When I do
api_call["shares"]
, It just returnsshares
.
This is because your response comes as a String
. Now on which you are calling String#[]
method. The docs str[match_str] → new_str or nil
says - If a match_str is given, that string is returned if it occurs in the string.
str['shares'] # => shares
This happened as per the documentation,as I mentioned. Your response string has a substring shares
, which is being returned as a method call String#[]
, in str['shares']
call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.