Search code examples
pythondjangojsonsimplejson

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.


Solution

  • 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()