How can you tell whether an HTTP response contains JSON?
Quick answer
Inspect the response’s Content-Type header for a JSON media type, such as application/json, and use it as a guide before parsing. Check the HTTP status separately: success does not prove that the body is JSON. Parsing can still fail if the body is unexpected or invalid, so handle that possibility rather than treating the header as a guarantee. [S1][S2]
The question, the details, the next step.
A practical checklist
Check the HTTP status separately from the body format.
Read the response’s Content-Type header; look for a JSON media type such as application/json.
Use the header to guide how you read the body, not as a guarantee that parsing will succeed.
Handle unexpected formats and JSON parsing failures explicitly.
When troubleshooting, note the status, header value, and a safe description of the body.
A few more useful answers
Can a response have a successful status but not contain JSON?
Yes. A successful status alone does not prove the body is JSON. Check Content-Type and handle the body according to the format you expect. [S1]
Does application/json in Content-Type guarantee valid JSON?
No. Content-Type describes the representation and helps guide parsing, but an unexpected or invalid body can still require error handling. [S1]
Should I check Content-Type when using Fetch?
Yes. In browser JavaScript using Fetch, check the response header before trying to read the body as JSON, and handle status and parsing separately. [S2]
Sources
References used for this guide.
- [S1] Content-Type header — HTTP | MDN developer.mozilla.org · Checked
- [S2] Using the Fetch API — Web APIs | MDN developer.mozilla.org · Checked
