How can i check if the file is empty?

Viewed 147

I want to check if the json file is empty. Where in the code do i check that properly? This is my code:

import os
import sys
import traceback
import json
import requests
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

try:
    API_ENDPOINT = os.getenv('OVERPASS_API_ENDPOINT', 'http://overpass.osm.ch/api/interpreter')

    query = "".join(sys.stdin.readlines())
    r = requests.get(API_ENDPOINT, params={'data': query})
    print(json.dumps(r.json(), sort_keys=True, indent=2))
except Exception as e:
    print("Error: %s" % e, file=sys.stderr)
    print(traceback.format_exc(), file=sys.stderr)
    sys.exit(1)

Thanks for your help.

1 Answers

Simple comparison with empty dict should do:

r.json() == {}

or

r.json() == dict()

or

len(r.json()) == 0

Edit: Seems like you may not be receiving a JSON in your response at all, to check that, you add this conditional:

if r.headers.get('content-type') == 'application/json':
    if r.json() == {}:
        # rest of your code
Related