Question

I am calling an API that returns an array of JSON objects and I cant seem to properly access each element. This is a sample return value of the API call

[{"param1":1,"param2":"blah1"},
{"param1":2,"param2":"blah2"},
{"param1":3,"param2":"blah3"}]

Here is me trying to call the API and print the first JSON response object's parameter

result = HTTParty.get('http://randomapi.com',query: options)
@a = result[0]['param1']
# puts "#{result}"
puts "#{@a}"

Doing this prints nothing. I know I am successfully accessing the URL because result will print the correct information.

I got information on how to access the JSON response through this URL http://blog.teamtreehouse.com/its-time-to-httparty

Edit: After reading comments below, I realized that the API call is returning a content type of text/html and parsing the text/html isnt working because the response is also returning the following header below the expected value. Is there any way to remove this without going into the string itself and stripping it out?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html 
    xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
        <form method="post" action="GetRankingList.aspx?pvptype=1&amp;sid=1&amp;tm=20130821160000&amp;auth=77c9b582c3aed3d3974400cfb118fe4b" id="form1">
            <div class="aspNetHidden">
                <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZLSAAAtd4/lj1u6b0GjPWM+p3i9tqI6sq+xDrRw2cAv3" />
            </div>
            <div></div>
        </form>
    </body>
</html>
Was it helpful?

Solution

It seems that the API returns a response with a Content-Type different from application/json. You can check that by printing:

puts result.content_type

If so, the HTTParty parser may be interpreting the response as a plain text; And, thus, the code result[0]['param1'] evaluates to nil Maybe you can try to parse the desired value into @a with:

@a = JSON.parse(result)[0]['param1']

Don't forget to require the json library

require 'json'

Good luck!

OTHER TIPS

You need to parse the parsed_response from the result.

@parsed = JSON.parse(result.parsed_response)

when accessing json with format

require 'json'
result = JSON.parse('[{"param1":1,"param2":"blah1"},{"param1":2,"param2":"blah2"}, {"param1":3,"param2":"blah3"}]')
@a = result[0]["param1"]
puts @a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top