NameError: name 'null' or 'json' is not defined in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
7 min

banner

# Table of Contents

  1. NameError: name 'null' is not defined in Python
  2. NameError: name 'json' is not defined in Python
  3. NameError: name 'true' or 'false' is not defined in Python

# NameError: name 'null' is not defined in Python

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.

nameerror name null is not defined

Here is an example of how the error occurs.

main.py
# โ›”๏ธ NameError: name 'null' is not defined val = null print(val)

# Use None instead of null in Python

To solve the error, we have to use None instead of null in Python.

main.py
val = None print(val) # ๐Ÿ‘‰๏ธ None

The None object is used to represent the absence of a value.

Make sure to replace all occurrences of null in your code with None.

# Parsing a JSON string into a native Python object

If you have a JSON string, you have to parse it to a native Python object before accessing specific properties.

main.py
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

parsing json string into native python object

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.

# Converting a Python object 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.

main.py
import json json_str = r'''{"name": null, "age": null}''' native_python_obj = json.loads(json_str) print(native_python_obj) # ๐Ÿ‘‰๏ธ {'name': None, 'age': None}

convert python object to json string

Notice that all null values become None after parsing the JSON string into native Python.

# Declaring a null variable in your code

Alternatively, you can declare a null variable and assign it a value of None.

main.py
null = None my_dict = {"name": null, "age": null} print(my_dict)

declaring a null variable in your code

However, note that this is a hacky solution and might be confusing to readers of your code.

# Parsing the response from the requests module

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.

main.py
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.

# NameError: name 'json' is not defined in Python

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.

nameerror name json is not defined

Here is an example of how the error occurs.

main.py
# โ›”๏ธ 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.

main.py
# โœ… 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.

Make sure you haven't used a capital letter j when importing json because module names are case-sensitive.

# Don't import the json module in a nested scope

Also, make sure you haven't imported json in a nested scope, e.g. a function.

main.py
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.

main.py
# โœ… 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.

# Make sure to not import the json module in a try/except statement

You also should be importing the json module in a try/except statement.

main.py
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.

# Importing specific functions from the json module

An alternative to importing the entire json module is to import only the functions and constants that your code uses.

main.py
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.

For example, when we use an import such as 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.

# NameError: name 'true' or 'false' is not defined in Python

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.

nameerror name true is not defined

Here is an example of how the error occurs.

main.py
# โ›”๏ธ 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.

main.py
# โ›”๏ธ NameError: name 'false' is not defined. Did you mean: 'False'? f = false print(f)

nameerror name false is not defined

# Use True and False in Python (capital first letter)

To solve the error, we have to use a capital T when spelling the True keyword.

main.py
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).

main.py
t = True print(t) # ๐Ÿ‘‰๏ธ True f = False print(f) # ๐Ÿ‘‰๏ธ False
There are only 2 boolean values - True and False.

The type of the two boolean values is <class 'bool'>.

main.py
print(type(True)) # ๐Ÿ‘‰๏ธ <class 'bool'> print(type(False)) # ๐Ÿ‘‰๏ธ <class 'bool'>

# Forgetting to parse JSON data into native Python objects

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.

main.py
# โ›”๏ธ 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.

main.py
json_str = {"is_subscribed": True, "is_admin": True}
Make sure to replace all occurrences of 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).

# Converting a JSON string to a Python object

If you are pasting a JSON string into your Python code, wrap it in quotes and mark it as a raw string.

main.py
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.

main.py
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.

# Converting a Python object to a JSON string

You can use the json.dumps method to serialize a Python object to a JSON formatted string.

main.py
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.

main.py
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.

main.py
print(int(True)) # ๐Ÿ‘‰๏ธ 1 print(int(False)) # ๐Ÿ‘‰๏ธ 0

You can use the not (negation) operator to invert a boolean value.

main.py
print(not True) # ๐Ÿ‘‰๏ธ False print(not False) # ๐Ÿ‘‰๏ธ True

You can use the built-in bool() function to convert any value to a boolean.

main.py
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:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev