How to resolve if https response is plain text or json format?


I trying to write response parser for my application and I stuck in place where some of endpoints can return plain string as a response in body instead of JSON format.
I’m using Jason library for that stuff.
eg. {:ok, Jason.decode!(body)}
When the body is JSON there is no problem, but when body contains plain string, decode raises error.
Is there any idea how to check wether body is json or plain text?
I don’t want to catch error for that purpose - I would like library to be generic.

The HTTP response should include a header that indicates what type the body is. Can you IO.inspect the headers in the response?

Well, that is an option. But I’m not sure if I can rely on that

A well-behaved server will set the Content-Type header on the response to the appropriate media type (e.g. application/json or text/plain). Failure to do so would break many clients, so I’d be surprised if such header wasn’t set properly.

If one really cannot rely on that, and the response can arbitrarily be JSON or plain text, I don’t see a better alternative to attempting to parse the JSON and catching errors.


Ok, thank you for answers.
I’ll use Content-Type.