3

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 Answers1

4

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
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • @ChristianNüssli please mark the answer as accepted to resolve the issue (click on tick mark) – Jarvis Dec 24 '20 at 08:47
  • Hi @Jarvis. Unfortunately every proposal you made didn't work with GH Actions. Any other solutions? – Christian Nüssli Dec 24 '20 at 08:55
  • What is the expected and actual output after adding the conditional? What do you mean by GH Actions? @ChristianNüssli Check the edited answer. – Jarvis Dec 24 '20 at 09:27
  • GH Actions = Github Actions... I try your last edit, one moment. – Christian Nüssli Dec 24 '20 at 12:47
  • Seems like didn't work :( 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)) if r.headers.get('content-type') == 'application/json': if r.json() == {}: except Exception as e: print("Error: %s" % e, file=sys.stderr) print(traceback.format_exc(), file=sys.stderr) sys.exit(1) – Christian Nüssli Dec 24 '20 at 12:51
  • What are you trying to get as output? What is the expected and actual outcome? – Jarvis Dec 24 '20 at 12:52
  • @ChristianNüssli the conditionals I added should be checked for before you print your json. – Jarvis Dec 24 '20 at 13:53
  • I tried it, but the action fails again. I receive every time a json, but sometimes, of the API isn't answering properly, the json file is empty. – Christian Nüssli Dec 24 '20 at 16:04