Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Peter Bengtsson: Cope with JSONDecodeError in requests.get().json() in Python 2 ...

$
0
0

Suppose you don't know with a hundred percent certainty that an API will respond in with a JSON payload you need to protect yourself.

This is how you do it in python 3:

import json import requests response = requests.get(url) try: print(response.json()) except json.decoder.JSONDecodeError: print("N'est pas JSON")

This is how you do it in Python 2:

import requests response = requests.get(url) try: print response.json() except ValueError: print "N'est pas JSON"

Here's how you make the code work across both:


Viewing all articles
Browse latest Browse all 9596

Trending Articles