How can I parse JSON responses with HTTParty?

HTTParty is a Ruby gem that makes http requests simple and fun. It also makes JSON parsing simple because if HTTParty detects that the response is JSON, it will automatically parse it for you.

Here is an example of how you can use HTTParty to make a GET request and parse the JSON response:

require 'httparty'

response = HTTParty.get('https://api.example.com/data.json')

# If the response Content-Type is 'application/json', 
# HTTParty will parse the JSON automatically. 
puts response.parsed_response

The parsed_response method will return the body of the response in the format it was received, in this case as a Ruby hash or array, depending on the structure of the JSON returned by the server.

If you want to ensure that the response is treated as JSON regardless of the Content-Type header, you can specify a parser like this:

require 'httparty'

class JsonParser < HTTParty::Parser
  def parse
    JSON.parse(body)
  end
end

response = HTTParty.get('https://api.example.com/data.json', parser: JsonParser)

puts response.parsed_response

In this case, the JsonParser class is used to force the response body to be parsed as JSON.

Keep in mind that if the server doesn't return a valid JSON response, you might get a JSON::ParserError. You should handle exceptions accordingly:

require 'httparty'

begin
  response = HTTParty.get('https://api.example.com/data.json')
  puts response.parsed_response
rescue JSON::ParserError => e
  puts "There was an error parsing the JSON: #{e.message}"
end

This will catch any JSON parsing errors and allow you to handle them, for example, by logging an error message or retrying the request.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon