Implicit conversion of HTTParty :: Response to String

When I try to parse some kind of answer in JSON, I get the following error. I raised JSON :: ParserError in my code if analysis failure is not possible. But such an exception does not fall under this parser error. I do not know why this error occurs? and how to save this error?

the code:

begin parsed_response = JSON.parse(response) rescue JSON::ParserError => e nil end 

Error:

 A TypeError occurred in background at 2014-11-16 03:01:08 UTC : no implicit conversion of HTTParty::Response into String 
+6
source share
1 answer

You get a TypeError . Occurs when you pass the wrong kind of argument to certain methods. You can save it like this:

 begin parsed_response = JSON.parse(response) rescue JSON::ParserError, TypeError => e puts e end 

I would not recommend this, though. The reason you get a TypeError is because JSON.parse requires a String object, and you passed it an HTTParty::Response object. Try giving it a String object instead. eg:

 parsed_response = JSON.parse(response&.body || "{}") 

Thus, the nil value in response or response.body returns a usable object. In this example, the object is an empty Hash , although you can replace the JSON string with any value that you want to represent with the value "not there" (for example, "[]" or "null" ).

+18
source

Source: https://habr.com/ru/post/1207002/


All Articles