Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse through a JSON file and pick out certain properties

I have a JSON file containing over 8000 features. An example of one is below:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"uuid":"____","part2":"_____","length":"529","function":"______"},"geometry":{"type":"LineString","coordinates":[[-360909.60698310119,7600968.922204642,0.0],[-361357.344715965,7600811.951385159,0.0],[-361805.08159795138,7600654.939420643,0.0]]}}

I am trying to use python to iterate through the features and print out certain aspects from the properties. At the minute I have the following code which is iterating through the features and printing the 1st feature and its properties 8420 times.


import json

# Opening JSON file
f = open('file.json')

# returns JSON object as
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data['features']:
    print(data["features"][0]["properties"])

How can I amend the above to show the features and properties for each of the 8420 features? I have tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for i in data['features']:
    print(data["features"][i]["properties"])

but I get the error TypeError: list indices must be integers or slices, not dict

>Solution :

i is a dictionary, not an index.

for i in data['features']:
    print(i["properties"])

If it was important to you to use an index, use enumerate or range:

for i, d in enumerate(data['features']):
    # data['features'][i] == d
for i in range(len(data['features'])):
    # data['features'][i] ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading