Storing data with JSON
(Read time is about 2 minutes)
So what is JSON?
Java Script Object Notation or JSON for short.
Websites like OpenWeather have an Application Programming Interface or API.
API's can return data in some common formats... like XML and JSON.
Python has modules that you can import into your program to use them and do advanced stuff.
What are some of the modules you can use?
Heres my list of ones I use and know regularly: (For simplistic sake I won't list everything I know or use)
- json (load and dump JSON data to files ect.)
- time (sleep a set amount of seconds)
- sys (provides a safe way to abort execution)
- os (provides Operating System commands/control, I.E. check to see if a file or directory exists, make a directory)
- pendulum (Advanced time/date handling)
- subproccess (for other OS commands)
- sqlachelmy (provides a cool way to interact with a database, and allows mutiple database types without needing to change much)
- sqlite (accesses sqlite 3 databases)
- pylint (Helps you write cleaner/clearer code)
So how do we do something like save something to a JSON file?
# My data dict
my_data = {
"name": "Beanzilla",
"pets_name": "Fishstick",
"fav_number": 9,
}
# Writing it all out in json
with open("example.json", "w") as f:
f.write(json.dumps(my_data, indent=4, sort_keys=True))
Ok so we now get a file called example.json that contains our information... now to load it back in
# Making the dict from the json file
with open("example.json", "r") as f:
my_data = json.loads(f.read())
Now we have a dict of our data accessing it is just the same.
print(my_data["name"])