Python - 'NoneType' object is not subscriptable (A Small Program For Steam Item Price)

Viewed 4771

So , i made this small program to update about the lowest_price of a specific item on steam market , it runs a loop and gets json response.

It works fine initially , displays the price , but after a while it shows the error.

The program code :

import json
import requests

def GetPrice () :

    response = requests.get ('https://steamcommunity.com/market/priceoverview/?appid=264710&currency=1&market_hash_name=Planet%204546B%20Postcard')

    json_data = {}
    json_data = json.loads (response.text)

    return json_data ["lowest_price"]

while True :

    print (GetPrice ())

Here is the output of the program :

$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
Traceback (most recent call last):
  File "C:\Users\Admin\Desktop\item_price.py", line 16, in <module>
    print (GetPrice ())
  File "C:\Users\Admin\Desktop\item_price.py", line 12, in GetPrice
    return json_data ["lowest_price"]
TypeError: 'NoneType' object is not subscriptable
[Finished in 20.2s]
4 Answers

This error occurs when you are trying to index an object that is of type None (i.e: the object has no value).

Here your None object is your json_data variable, which means that json.loads (response.text) returns None.

You can avoid this error by adding an if statement that will check if the value is not None:

if json_data is not None:
    return json_data['lowest_price']
return None

Or with a try-except statement:

try:
    return json_data['lowest_price']
except Exception as e:
    return None    # or you can raise an exception if you want

You're experiencing this problem since you're making too many requests to the server really fast.

To be specific, the server replies with http error code 429

Consider waiting for a few seconds before sending successive requests.

Check your variable holding correct data. if json_data holding nothing then you can not retrieve the value. Say, json_data is None you need to check the variable.

Approach 1

try:
    return json_data["lowest_price"]
except Exception as e:
    print(json_data)
    print(e)
    return None

Approach 2

You can check json_data variable value explicitly

if json_data != None:
    if "lowest_price" in json_data:
        return json_data["lowest_price"]

So sometimes you are receiving empty response which is causing issue

try:
    price = json_data ["lowest_price"]
except Exception as e:
    pass
Related