2

I am trying to iterate JSON objects and append selected features to new GeoJSON using geojson Python library. When hardcoded the script works fine. But when append method is used in a for loop I get this error.

TypeError: string indices must be integers

Why does this work (polygon variable hardcoded and taken from print statement in the loop)...

polygon = Polygon([[[-112.30701948248064, 33.65181795979867], [-112.30701798409073, 33.651669879089], ...[-112.30701948248064, 33.65181795979867]]])

features = []
features.append(Feature(geometry=polygon, properties={"country": "Spain"}))
feature_collection = FeatureCollection(features)

But this does not...

with open(subs) as f:
   data = json.load(f)

for feature in data['features']:
   if feature['properties']['PUC'] == '0261':
      polygon = 'Polygon(' + str(feature['geometry']['coordinates']) + ')'
      features.append(Feature(geometry=polygon, properties={"country": "Spain"}))

2 Answers 2

2

The problem is you need to provide an instance of the Polygon class as as a geometry to the Feature class.

  • In your hardcoded example, you are giving actual coordinates as a geometry.
  • In the for loop, you are converting the coordinates to a str type and giving the polygon in a Well Known Text (WKT) format to the Feature class.

So normally your problem will be solved when you use this code instead:

with open(subs) as f:
    data = json.load(f)

for feature in data['features']:
    if feature['properties']['PUC'] == '0261':
        polygon = Polygon(feature['geometry']['coordinates'])
        features.append(Feature(geometry=polygon, properties={"country": "Spain"}))
1
  • Ughh. Thank you @Thibauld. Your solution works well. Here I am trying too hard again. Commented Dec 26, 2019 at 23:34
0

I've seen this issue when the iterable object in the for loop is expected to be an integer instead of a string. I would check what the actual Json output really is, your "data" variable to make sure you're getting exactly what you're expecting. Try breaking down the for loop to it's simplest by commenting out unnecessary code for the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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