Check if the key exists or not in JSON in Python
Let’s use this JSON as an example.
{ "name_html": "", "mkc": 1, "kills": 4, "deaths": 10, "lastCharacter": "Spaz", "lastName": "Bolt", "rank": 2, "games": 5, "scores": 170, "aid": "pb-IF4lVFFfNQ==" }
I would like to find out if rank key is already in this JSON. To check if a key exists in a JSON, we can use in keyword like below.
import json scoreJson ="""{ "name_html": "", "mkc": 1, "kills": 4, "deaths": 10, "lastCharacter": "Spaz", "lastName": "Bolt", "rank": 2, "games": 5, "scores": 170, "aid": "pb-IF4lVFFfNQ==" }""" print("Checking if rank key exists in JSON") scores = json.loads(scoreJson) if "rank" in scores: print("Rank already calculated") else: print("Rank doesn't exist in JSON data. Let's calculate")