I am trying to extract the name, longitude and latitude from a json file and convert it into a new .csv file with the columns cityname | longitude | latitude
from this json: https://www.submarinecablemap.com/api/v3/landing-point/landing-point-geo.json
def cables():
# print(page.text)
# print(page2.text)
# print(page3.text)
json_file = 'exitpoints.json'
with open(json_file) as json_data:
data = json.load(json_data)
# print(data)
print("City: ", data['features.name'])
#print("Longitude: ", data['0'])
#print("Latitude: ", data['1'])
i tried all kinds of combinations data[features].data[name] etc…
how do i get this?
5
Answers
In order for you to get the lat and long, you need to first iterate the
features
list and then unpack thecoordinates
You can do it like this, the traversal of the json is working like this, where you can get the name, longitude and latitude as well.
Full example
you can do it like this for example.
It assumes that you know that your data of interest in the ‘features’ list.
Now each row in
csv_list
contains the name, lon and lat as string. Delimiter is;
since,
is used in the name.You can also use
SimpleNamespace
Here you go friend, I’ve written the soluton in form of a script for you, but you can put it in a function too.
It helps that you pretify your JSON so you can understand the structure of it. There are several online prettifiers, but I often use this one: https://jsonformatter.curiousconcept.com/
When you pretify the JSON you’ve provided it is instantly evident that all of the desired cities with the coordinates are in the
features
array.Next you need to open a json file for reading and a csv file for writing. Then you load the json like you already did, but you also prepare the csv dictionary writer and write a header to it.
Then you go through each item in the json and take what you need and write it into the csv file. In the end you close the files, you don’t have to, but it’s a good practice.
This script will create the CSV file named
exitpoints.csv
with the colums you’ve requestedcityname|longitude|latitude
.To run it, don’t forget to
chmod +x
make it executable if you are using a Unix based system.Cheers! 🍻