· 5 years ago · Nov 18, 2020, 08:00 AM
1"""
2PYTHON 103 - 2.8 An introduction to JSON
3
4Creating a JSON data structure
5JSON is remarkably similar to Python’s dictionary data type, in that it uses a
6key–value pairing to store data. To demonstrate this you will create a project
7that will store the details of the first person on the moon,
8Neil Armstrong, using a JSON structure.
9
10This program first imports the json library, enabling us to use JSON with Python.
11It then creates a dictionary called data storing three values.
12The first key is Name and the value it references is the name of astronaut Neil Armstrong,
13stored as a string. The next key is Age and the value stored here is Neil’s age at the
14time of his death, stored as an integer.
15The last key is Hobbies and the value for this is a list of his hobbies, each stored as a string.
16"""
17
18import json
19data = {
20"Name": "Neil Armstrong",
21"Age": 82,
22"Hobbies" : ["Aircraft design", "Fishing", "Astronaut"]
23}
24
25"""
26To create persistent data storage of this information you use the standard file open method,
27which will create a new writable file, neil.json, and the json.dump function, which will write
28the dictionary to that file in JSON format. Run the code yourself, and then open neil.json using
29a text editor.The contents should look like this:
30"""
31
32with open("neil.json","w") as f:
33 json.dump(data,f)
34
35
36"""
37Notice that the JSON syntax is identical to Python’s dictionary.
38Try importing the JSON data back into the program using the following code.
39This opens the JSON file in read "r" mode, and uses the json.load method to read the JSON file.
40You should see that data2 is a dictionary, the same as data.
41You can obtain the values from this dictionary by using the relevant keys, as you saw earlier this week
42"""
43
44with open("neil.json", "r") as f:
45 data2 = json.load(f)
46print(data2)
47
48
49"""
50Using JSON with a public API
51
52To work with data from the internet you can use the requests library,
53which allows you to send and receive data over a network connection.
54
55This example uses the requests library to get data from the NASA API and
56store it into an object r. The data in r is then parsed from JSON data into
57a Python dictionary using r.json().
58The entire dictionary structure is then printed to the REPL.
59In the structure of this dictionary you would see many keys,
60one of which is explanation — the associated value provides a text description of an astronomical image.
61"""
62
63import requests
64r = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
65NASA = r.json()
66print(NASA)
67