D-Nice
D-Nice

Reputation: 4870

How to validate JSON with simplejson

Occasionally I'm querying a server for JSON and receiving a 404 HTML page when the requested data is not available.

Thus, I must have a check to ensure that the JSON I'm expecting, is actually json rather than HTML. I'm accomplishing this now by checking for a string that I can expect to be in the HTML is contained in the response, but I think there has to be a better way to do this.

Upvotes: 1

Views: 852

Answers (2)

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

You should be able to tell that you recieved a 404, because the response code was not 200. That is:

import urllib
resp = urllib.urlopen('http://example.com/')

if resp.getcode() == 200:
    rejoice()
if resp.getcode() == 404:
    sulk()

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798616

Find the first non-whitespace character. If it's "<" then you have HTML.

Also, check the content type header and HTTP status code.

Upvotes: 2

Related Questions