what is json?
jason is a module for python that allows a user to 'sterilize' data to use later or even in entirely different scripts.
Im going to be honest there are better options out there but json is very simple compared to most of the other ways to save data
1) how to get json
2) how to save data
3) how to load data
4) handling errors
5) quick review and full example
how to get json
To get json all you need to do (on repl.it) is
Sometimes on other IDEs you need to install it by going to the
terminal and entering
pip install json
how to save data
Saving data with
json is fairly simple.
First you need to make sure you have it imported/installed
1. Use the function
open to open a file, im just going to use the name 'example.txt` to show where to put the example
- Inside the
openadd your filename (dont forget the (
') or (
- Add what you want to do with the file.
Add which letter then
- In the next line you will add
4.5. Inside the
dump() add the item you want to save and
json cant save all data!
json can save the following.
json cannot save
You have completed the 'how to save data' portion
So now you have your stuff saved, you want to use it again
- We are going to use the same thing up to the start of
'outfile'and replace it with
infileand completely leave behind the
- Instead of
json.dumpwe will use
json.load(infile)after a variable name
what errors to expect
The most common errors i get is
FileNotFoundError is an error you get if you try to load a file that doesn't exist
This is common as a typo.
To pervent yourself from getting this error you have to learn how to handle errors, this can be done with
try will try to do anything that follows (before the next indent block or
except will wait for a given error and if it receives it it does whats after it (before next indent block)
These two follow the syntax of
that file doesn't exist
Because if we are loading
x from the other examples it is saved to the file
number.txt meaning the file
number.txt doesn't exist causing a
FileNotFoundError but because
FileNotFoundError was put after the
except it didnt stop the program.
import json adds json to your script
with open() opens the file name
json.dump saves data
json.load loads in saved data
try/else pervents an error
Loading into the same script
Save/load in different scripts
If there are spelling miscakes or inaccuracies let me know, i made this in a rush.