Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
The Python "NameError: name 'false' is not defined" occurs when we use false
instead of False
in Python or we forget to parse JSON data into native Python
objects. To solve the error, replace any occurrences of false
with False
in
your code.
Here is an example of how the error occurs.
# ⛔️ NameError: name 'false' is not defined. Did you mean: 'False'? json_str = {"is_subscribed": false, "is_admin": false}
One way to solve the error is to replace all occurrences of false
with
False
.
json_str = {"is_subscribed": False, "is_admin": False}
false
in your code with False
.If you are pasting a JSON string into your Python code, wrap it in quotes and mark it as a raw string.
import json json_str = r'''{"is_subscribed": false, "is_admin": false}''' # 👇️ convert JSON string to native Python object native_python_obj = json.loads(json_str) print(native_python_obj) # 👉️ {'is_subscribed': False, 'is_admin': False}
We used the json.loads method to deserialize a JSON string to a native Python object.
When we parse a JSON string into a Python object, all false
values become
False
.
Alternatively, you can declare a false
variable and assign it a value of
False
.
false = False my_dict = {"is_subscribed": false, "is_admin": false}
However, note that this is a hacky solution and might be confusing to readers of your code.
You can use the json.dumps method to serialize a Python object to a JSON formatted string.
import json # ✅ convert Python object to JSON json_str = json.dumps({"is_subscribed": False, "is_admin": False}) print(json_str) # 👉️ {"is_subscribed": false, "is_admin": false} print(type(json_str)) # 👉️ <class 'str'> # ✅ Parse JSON string to Python object native_python_obj = json.loads(json_str) print(native_python_obj) # 👉️ {'is_subscribed': False, 'is_admin': False} print(type(native_python_obj)) # 👉️ <class 'dict'>
Notice that False
becomes false
when a Python object gets converted to a
JSON string.
Conversely, when we parse the JSON string to a native Python object, false
becomes False
.
If you use the requests module to make
HTTP requests, you can call the json()
method on the response object to parse
the JSON string into a native Python object.
import requests def make_request(): res = requests.get('https://reqres.in/api/users') print(type(res)) # 👉️ <class 'requests.models.Response'> # ✅ Parse JSON to native Python object parsed = res.json() print(parsed) print(type(parsed)) # 👉️ <class 'dict'> make_request()
The res
variable is a Response
object that allows us to access information
from the HTTP response.
We can call the json()
method on the Response
object to parse the JSON
string into a native Python object which would convert any false
values to
their Python equivalent of False
.