Last updated: Apr 8, 2024
Reading timeยท7 min
The Python "NameError: name 'null' is not defined" occurs when we use null
instead of None
in Python or we forget to parse JSON data into native Python
objects.
To solve the error, replace any occurrences of null
with None
in your
code.
Here is an example of how the error occurs.
# โ๏ธ NameError: name 'null' is not defined val = null print(val)
None
instead of null
in PythonTo solve the error, we have to use None
instead of null
in Python.
val = None print(val) # ๐๏ธ None
The None object is used to represent the absence of a value.
null
in your code with None
.If you have a JSON string, you have to parse it to a native Python object before accessing specific properties.
import json json_str = json.dumps({'name': None}) print(json_str) # ๐๏ธ '{"name": null}' print(type(json_str)) # ๐๏ธ <class 'str'> # โ Parse JSON string to native Python object native_python_obj = json.loads(json_str) print(native_python_obj) # ๐๏ธ {'name': None} print(type(native_python_obj)) # ๐๏ธ <class 'dict'> print(native_python_obj['name']) # ๐๏ธ None
We used the json.dumps method to serialize a Python object to a JSON formatted string.
Notice that None
becomes null
when converted to a JSON string.
Conversely, you can use the json.loads method to deserialize a JSON string to a native Python object.
When we parse a JSON string into a Python object, null
values become None
.
If you have a JSON string in your code, you can use the json.loads()
method to
convert it to a Python object.
import json json_str = r'''{"name": null, "age": null}''' native_python_obj = json.loads(json_str) print(native_python_obj) # ๐๏ธ {'name': None, 'age': None}
Notice that all null
values become None
after parsing the JSON string into
native Python.
null
variable in your codeAlternatively, you can declare a null
variable and assign it a value of
None
.
null = None my_dict = {"name": null, "age": null} print(my_dict)
However, note that this is a hacky solution and might be confusing to readers of your code.
requests
moduleIf 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', timeout=10) 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 null
values to
their Python equivalent of None
.
The Python "NameError: name 'json' is not defined" occurs when we use the
json
module without importing it first.
To solve the error, import the json
module before using it -
import json
.
Here is an example of how the error occurs.
# โ๏ธ NameError: name 'json' is not defined json_str = json.dumps({'name': 'Bobby Hadz', 'age': 30})
To solve the error, we have to import the json module.
# โ Import the json module first import json json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29}) print(json_str) # ๐๏ธ '{"name": "Bobby Hadz", "age": 29}' print(type(json_str)) # ๐๏ธ <class 'str'> native_python_obj = json.loads(json_str) print(native_python_obj) # ๐๏ธ {'name': 'Bobby Hadz', 'age': 29} print(type(native_python_obj)) # ๐๏ธ <class 'dict'>
Even though the json
module is in the Python standard library, we still have
to import it before using it.
j
when importing json
because module names are case-sensitive.json
module in a nested scopeAlso, make sure you haven't imported json
in a nested scope, e.g. a function.
def get_json(): import json json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29}) print(json_str) # โ๏ธ NameError: name 'json' is not defined json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29})
We imported the json
module in a function, so we aren't able to use it outside
of the function.
Import the module at the top level to be able to use it throughout your code.
# โ Moved the import to the top of the file import json def get_json(): json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29}) print(json_str) json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29})
The import statement should be at the top of your file, before any lines that
make use of the json
module.
json
module in a try/except statementYou also should be importing the json
module in a
try/except statement.
import json try: # ๐๏ธ Code here could raise an error json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29}) print(json_str) except ImportError: json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29}) json_str = json.dumps({'name': 'Bobby Hadz', 'age': 29})
The code sample works, however, if the code in the try
statement raises an
error, the json
module won't get imported successfully.
This would cause the error because we are trying to access properties on the
json
module in the outer scope and the except
block.
json
moduleAn alternative to importing the entire json
module is to import only the
functions and constants that your code uses.
from json import dumps, loads json_str = dumps({'name': 'Bobby Hadz', 'age': 29}) print(json_str) # ๐๏ธ '{"name": "Bobby Hadz", "age": 29}' print(type(json_str)) # ๐๏ธ <class 'str'> native_python_obj = loads(json_str) print(native_python_obj) # ๐๏ธ {'name': 'Bobby Hadz', 'age': 29} print(type(native_python_obj)) # ๐๏ธ <class 'dict'>
The example shows how to import only the dumps
and loads
functions from the
json
module.
Instead of accessing the members on the module, e.g. json.loads
, we now access
them directly.
You should pick whichever approach makes your code easier to read.
import json
, it is much harder to see which functions from the json
module are being used in the file.Conversely, when we import specific functions, it is much easier to see which
functions from the json
module are being used.
However, you will most likely be using only 2 functions from the json
module -
json.dumps()
and json.loads()
.
The json.dumps function is used to serialize a Python object to a JSON formatted string.
Conversely, you can use the json.loads function to deserialize a JSON string to a native Python object.
You can view all of the functions the json
module provides by visiting the
official docs.
The Python "NameError: name 'true' is not defined" occurs when we misspell the
keyword True
.
To solve the error, make sure to capitalize the first letter of the keyword -
True
.
Here is an example of how the error occurs.
# โ๏ธ NameError: name 'true' is not defined. Did you mean: 'True'? t = true print(t)
You might also get the error when you forget to capitalize the letter F
in
False
.
# โ๏ธ NameError: name 'false' is not defined. Did you mean: 'False'? f = false print(f)
True
and False
in Python (capital first letter)To solve the error, we have to use a capital T
when spelling the True
keyword.
t = True print(t) # True
Names of variables, functions, classes and keywords are case-sensitive in Python.
The only other available
boolean value
is False
(capital F
).
t = True print(t) # ๐๏ธ True f = False print(f) # ๐๏ธ False
True
and False
.The type of the two boolean values is <class 'bool'>
.
print(type(True)) # ๐๏ธ <class 'bool'> print(type(False)) # ๐๏ธ <class 'bool'>
The error also commonly occurs when we forget to parse JSON data into native Python objects.
Here is an example of how the error occurs.
# โ๏ธ NameError: name 'true' is not defined. Did you mean: 'True'? json_str = {"is_subscribed": true, "is_admin": true}
To solve the error, replace any occurrences of true
with True
in your code.
json_str = {"is_subscribed": True, "is_admin": True}
true
in your code with True
.Do the same for false
. Make sure to replace all occurrences of false
in your
code with False
(capital first letter).
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": true, "is_admin": true}''' # ๐๏ธ Convert the JSON string to native Python object native_python_obj = json.loads(json_str) print(native_python_obj) # ๐๏ธ {'is_subscribed': True, 'is_admin': True}
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 true
values become
True
.
Alternatively, you can declare a true
variable and assign it a value of
True
.
true = True my_dict = {"is_subscribed": true, "is_admin": true}
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 the Python object to JSON json_str = json.dumps({"is_subscribed": True, "is_admin": True}) print(json_str) # ๐๏ธ {"is_subscribed": true, "is_admin": true} print(type(json_str)) # ๐๏ธ <class 'str'> # โ Parse the JSON string to Python object native_python_obj = json.loads(json_str) print(native_python_obj) # ๐๏ธ {'is_subscribed': True, 'is_admin': True} print(type(native_python_obj)) # ๐๏ธ <class 'dict'>
Notice that True
becomes true
when a Python object gets converted to a JSON
string.
Conversely, when we parse the JSON string to a native Python object, true
becomes True
.
Boolean objects in Python are implemented as a subclass of integers.
print(isinstance(True, int)) # ๐๏ธ True print(isinstance(False, int)) # ๐๏ธ True
Converting a True
boolean value to an integer
returns 1
, whereas converting False
returns 0
.
print(int(True)) # ๐๏ธ 1 print(int(False)) # ๐๏ธ 0
You can use the not
(negation) operator to invert a boolean value.
print(not True) # ๐๏ธ False print(not False) # ๐๏ธ True
You can use the built-in bool()
function to convert any value to a boolean.
print(bool(1)) # ๐๏ธ True print(bool('bobbyhadz.com')) # ๐๏ธ True print(bool('')) # ๐๏ธ False print(bool(0)) # ๐๏ธ False
The
bool()
function takes a value and converts it to a boolean (True or False). If the
provided value is falsy or omitted, then bool
returns False
, otherwise it
returns True
.
All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).The bool()
function returns True
if passed any non-falsy value.