I have the following code that I am using to open the above json file and extract the data. However, I only want the coordinate data, but the code gives me the following error.
TypeError: string indices must be integers
.
How would I print out just the coordinates data?
{
"type": "Polygon",
"coordinates": [
[
[
-5.84731,
60.5832
],
[
-5.93843,
60.5832
],
[
-2.39097,
60.5832
],
[
-2.39097,
60.5843
],
[
-2.75097,
60.5823
]
]
]
}
import json
f = open('allData.json')
data = json.load(f)
print(data['type']['coordinate'])
f.close()
CodePudding user response:
print(data['type']['coordinate'])
This is fetching data['type']
first, = "Polygon", and then applying index ['coordinate']
to that, hence the error you're getting about indexing a string.
coordinates (plural) is not a child of type in your structure. You want data['coordinates']
.
CodePudding user response:
You just need to call the coordinates
import json
f = open('allData.json')
data = json.load(f)
print(data['coordinates'])
f.close()
Output
[[[-5.84731, 60.5832], [-5.93843, 60.5832], [-2.39097, 60.5832], [-2.39097, 60.5843], [-2.75097, 60.5823]]]