What JSON is and why Python reads it easily
A JSON file is a text file that stores data in a format Python understands natively. JSON stands for JavaScript Object Notation, but it works just as well in Python. The file ends in .json and contains data organized as lists, dictionaries, numbers, and text — the same structures Python uses internally.
Python has a built-in module called json that converts JSON text into Python objects you can work with when ready. You do not need to install anything extra. When you read a JSON file, Python turns it into a dictionary or list that you can loop through, search, or modify like any other Python data structure.
This matters for file organization because JSON files are human-readable — you can open one in a text editor and see what is inside — but they are also structured enough that a program can parse them reliably. If you are storing configuration settings, lists of items, or exported data from another program, JSON is often the format you will encounter.
Key Takeaways
- The json module is built into Python, so you import it at the top of your script with import json.
- Use json.load() to read a JSON file directly from disk, or json.loads() to convert a JSON string that is already in memory.
- After reading, the JSON data becomes a Python dictionary or list that you can access with bracket notation or loop through with for statements.
- If the JSON file is malformed or the path is wrong, Python will raise an error with a specific message telling you what went wrong.
The simplest way: json.load() with open()
The most common pattern is to open the file, read it with the json module, and close it automatically. Here is the exact code:
import json with open('myfile.json', 'r') as file: data = json.load(file)Break this down: import json loads the module. with open() opens the file in read mode ('r') and assigns it to the variable file. The with statement ensures the file closes automatically when the block ends, even if an error occurs. json.load(file) reads the file and converts it to a Python object — usually a dictionary.
After this, data contains your JSON as a Python structure. If your JSON file contains a list of objects, data will be a list. If it contains a single object, data will be a dictionary. You can now access values with bracket notation: data['key'] or data[0] for lists.
When the JSON is already a string in your code
Sometimes you have JSON text already in memory — perhaps you received it from a web request or copied it from somewhere. Use json.loads() instead (note the s at the end, which stands for "string"):
import json json_string = '{"name": "Alice", "age": 30}' data = json.loads(json_string) print(data['name']) # Output: AliceThe difference is straightforward: json.load() reads from a file object, json.loads() reads from a string. Everything else works the same way — the result is a Python dictionary or list you can use when ready.
Accessing data after you read it
Once you have read the JSON, you interact with it like any Python data structure. If your JSON is a dictionary, use keys to get values. If it is a list, use index numbers:
import json with open('person.json', 'r') as file: person = json.load(file) # If person.json contains: {"name": "Bob", "age": 25, "city": "Portland"} print(person['name']) # Output: Bob print(person['age']) # Output: 25If your JSON contains nested structures — a dictionary inside a dictionary, or a list inside a dictionary — chain the brackets together:
import json with open('company.json', 'r') as file: company = json.load(file) # If company.json contains: {"name": "Acme", "employees": [{"name": "Alice"}, {"name": "Bob"}]} print(company['employees'][0]['name']) # Output: AliceYou can also loop through lists or dictionary keys using for loops, just as you would with any Python list or dictionary.
Handling errors when the file does not exist or is broken
If the file path is wrong or the JSON is malformed, Python raises an error. You can catch these with a try and except block:
import json try: with open('myfile.json', 'r') as file: data = json.load(file) except FileNotFoundError: print("The file was not found.") except json.JSONDecodeError: print("The file is not valid JSON.")FileNotFoundError means the file does not exist at that path. json.JSONDecodeError means the file exists but contains invalid JSON — perhaps a missing comma, mismatched brackets, or unquoted text. The error message will tell you the line number where the problem starts.
If you are reading many files or want to be thorough, wrap the entire operation in error handling. For quick scripts where you know the file is correct, the try-except block is optional but recommended.
Reading JSON from a file path that changes
If your JSON file is in a different folder, include the path in the filename. Use forward slashes even on Windows — Python handles them correctly:
import json with open('data/settings.json', 'r') as file: settings = json.load(file)If the path is absolute (starts from the root of your computer), include the full path:
import json with open('/Users/yourname/Documents/myfile.json', 'r') as file: data = json.load(file)On Windows, you can also use backslashes, but you must either escape them (C:\\Users\\yourname\\file.json) or use a raw string (r'C:\Users\yourname\file.json'). Forward slashes work everywhere and are simpler.
Writing JSON back to a file
After you read and modify JSON data, you often want to save it. Use json.dump() to write a Python object back to a JSON file:
import json data = {'name': 'Charlie', 'age': 28} with open('output.json', 'w') as file: json.dump(data, file)The syntax mirrors json.load(): pass the Python object first, then the file object. The file opens in write mode ('w') instead of read mode. If the file does not exist, Python creates it. If it does exist, Python overwrites it.
To make the output more readable with indentation, add the indent parameter:
json.dump(data, file, indent=2)This adds two spaces of indentation to each level, making the file easier to read in a text editor.
Frequently Asked Questions
What is the difference between json.load() and json.loads()?
json.load() reads from a file object that you have already opened. json.loads() reads from a string that is already in memory. Use load() when you are reading from disk, and loads() when you have JSON text as a variable in your code.
Can I read a JSON file that contains a list instead of a dictionary?
Yes. json.load() returns whatever the top level of the JSON is — a dictionary, a list, a string, or a number. If your JSON file starts with [ instead of {, the result will be a list. Access it with index numbers: data[0], data[1], and so on.
What does JSONDecodeError mean?
It means the file contains text that is not valid JSON. Common causes are missing commas between items, unquoted text, single quotes instead of double quotes, or mismatched brackets. The error message includes the line number where Python stopped being able to parse. Open the file in a text editor and check that line.
Do I have to use a with statement?
No, but you should. You can write file = open('myfile.json', 'r') and then file.close() later, but the with statement closes the file automatically even if an error occurs. This prevents resource leaks and is considered best practice in Python.
Can I read a JSON file that is very large?
json.load() reads the entire file into memory at once. For files larger than your available RAM, this will fail. For very large JSON files, you would need to read and process the file line by line or use a streaming JSON parser, which is beyond the scope of basic file reading. Most JSON files you encounter are small enough for json.load() to handle.