23

I have have geojson data from a query which I now want to parse and print on screen. My current code is:

import urllib
import geojson

while True:

    url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2017-03-01&minmagnitude=4.0&maxmagnitude=9.0&minlongitude=5.95&maxlongitude=10.50&minlatitude=45.81&maxlatitude=47.81'
    uh = urllib.urlopen(url)
    data = uh.read()
    print data
    break

It seems that data is a simple string. However, I thought it could be parsed like a json parameter. How do I have to handle geojson data in order to print a single point, e.g. to extract the coordinates of the first point only?

stonebe
  • 482
  • 1
  • 3
  • 14

5 Answers5

51
import geojson
with open(path_to_file) as f:
    gj = geojson.load(f)
features = gj['features'][0]
31

You can read it like any json:

import json
data = json.loads(datastring)
data['features'][0]['geometry'] #Your first point
Jesse Bakker
  • 2,403
  • 13
  • 25
  • 2
    if loading from a file: use data = json.load(fileobject) – onxx Apr 15 '21 at 18:04
  • This is what I am searching for. When I use your solution, I get a dict which looks like this `0 MultiLineString [[[8.5551415, 49.8598025], [8.5563399, 49.8598...` with 3 columns. As you can see the third column has the coordinates I want. Do you know by any chances how I can transfer the coordinates into a dataframe with latitude and longitude as seperate colums since the values represent this? – Gobrel Jan 04 '22 at 23:09
22

You can also use geopandas:

import geopandas as gpd
earthquake = gpd.read_file('earthquake.geojson')
print(earthquake.head())
sagarr
  • 1,152
  • 1
  • 9
  • 16
5

You can read it with json import, and file open:

import json
with open(path) as f:
    data = json.load(f)
for feature in data['features']:
    print(feature['properties'])
poetyi
  • 236
  • 4
  • 13
4

You can use pandas library directly

import pandas as pd
data = pd.read_json('File.geojson')

The important this is to understand the structure of this json file and manipulate the dictionaries in there

Himanshu Aggarwal
  • 163
  • 1
  • 1
  • 5