Mapping Global Data Sets - Json
Mapping Global Data Sets - Json
{"type":"FeatureCollection","metadata":{"generated":15503614610
00,...
{"type":"Feature","properties":{"mag":1.2,"place":"11km NNE of
Nor...
{"type":"Feature","properties":{"mag":4.3,"place":"69km NNW of
Ayn...
{"type":"Feature","properties":{"mag":3.6,"place":"126km SSE of
Co...
This file is formatted more for machines than it is for humans.
But we can see that the file contains some dictionaries, as well as
information that we’re interested in, such as earthquake
magnitudes and
locations.
The json module provides a variety of tools for exploring and
working with JSON data.
There are
i) load
ii)dump
Examining Json Data:
import json
readable_file = 'data/readable_eq_data.json'
with open(readable_file, 'w') as f:
json.dump(all_eq_data, f, indent=4)
We first import the json module to load the data properly from
the file, and then store the entire set of data in all_eq_data. The
json.load() function converts the data into a dictionary.
Next we create a file to write this same data into a more readable
format. The json.dump() function takes a JSON data object and a
file object, and writes the data to that file.
The indent=4 argument tells dump() to format the data using
indentation that matches the data’s structure.
Making a list of all earthquakes:
The first part of the file includes a section with the key
"metadata". This tells us when the data file was generated and
where we can find the data online.
It also gives us a human-readable title and the number of
earthquakes included in this file.
In this 24-hour period, 158 earthquakes were recorded.
This geoJSON file has a structure that’s helpful for location-based
data.
Making a list of all earthquakes:
he following program makes a list that contains all the
information about every earthquake that occurred:
import json
all_eq_dicts = all_eq_data[‘metadata']
all_eq=all_eq_dicts[‘count’]
Extracting Magnitudes:
The key "properties" contains a lot of information about each
earthquake. We’re mainly interested in the magnitude of each quake,
which is associated with the key "mag".
The program pulls the magnitudes from each earthquake.
mags = []
for eq_dict in all_eq_dicts:
mag = eq_dict['properties']['mag']
mags.append(mag)
print(mags[:10])
Now we’ll pull the location data for each earthquake, and then we can
make a map of the earthquakes.
The location data is stored under the key "geometry". Inside the
geometry dictionary is a "coordinates" key, and the first two values in
this list are the longitude and latitude.
The following program pulls the location data: