5

Is there a best way to determine the number of features in a GeoJSON file?

Ideally using Python or JavaScript.

2 Answers 2

9

If you have GeoJson that looks like that on the wikipedia page

var json={
  "type": "FeatureCollection",
  "features": [
   {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [102.0, 0.6]
   },
    "properties": {
      "prop0": "value0"
    }
  },
 {
   "type": "Feature",
   "geometry": {
      "type": "LineString",
      "coordinates": [
         [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
      ]
  },
    "properties": {
      "prop1": 0.0,
      "prop0": "value0"
    }
  },
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
        "coordinates": [
          [
            [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0],
            [100.0, 0.0]
          ]
        ]
   },
    "properties": {
      "prop1": {
        "this": "that"
     },
      "prop0": "value0"
    }
   }
  ]
}

then all you need to do is:

json.features.length

as this is a native Javascript object and so the embedded feature array has a length property, which in this case is 3.

If you want to do this in Python, you can use json.loads(your_json) see https://docs.python.org/2/library/json.html, which will parse the json into dictionaries and lists, so you can again get the value of the length of the list containing the features.

5

In Python:

import json #(geojson also fine)
from __future__ import print_function  # for Python 2.x compatibility

json_data = open('a.geojson')
data = json.load(json_data)
print(len(data['features']))
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.