Reputation: 97
So I have JSON file that contains 4 coordinates of a square. The JSON tree starts off with the index of the squares ID (1, 2, 3... etc) and within each ID we have 4 sets of coordinates (x1,y1 etc). My end goal is to be able to build up an array of coordinates, however, I am unable to access the keys that have the coordinates labeled (x1,y1) and I am not sure what I am doing wrong? Any help would be greatly appreciated
main.py
with open('data.json','r') as json_file:
coordinates = json.load(json_file)
# We get the length of the number of objects within the json representation
temp_length = len(coordinates)
# For each square, access the coordinates
for x in range (0, temp_length):
for y in coordinates[x][0]['x1,y1']:
print(y)
data.json
[
{
"1": [
{
"x1,y1": [
[
598,
326
]
],
"x2, y2": [
[
598,
370
]
],
"x3, y3": [
[
793,
367
]
],
"x4, y4": [
[
793,
303
]
]
}
]
},
{
"2": [
{
"x1,y1": [
[
1005,
170
]
],
"x2, y2": [
[
1005,
308
]
],
"x3, y3": [
[
1130,
293
]
],
"x4, y4": [
[
1129,
169
]
]
}
]
}
]
Producing this error when running the above :
Traceback (most recent call last):
File "/Users/main.py", line 35, in <module>
main()
File "/Users/main.py", line 20, in main
for y in coordinates[x][0]['x1,y1']:
KeyError: 0
Upvotes: 0
Views: 55
Reputation: 1123400
You are passing integers to a dictionary that only has string keys. 0
is not the same thing as "0"
, and your sample data doesn't even have a "0"
key (only "1"
and "2"
are present).
Don't generate integers. Just loop over the values or items of the dictionary:
for square_id, nested_list in coordinates.items():
for coord in nested_list[0]['x1,y1']:
print("ID:", square_id)
print("Coordinate:", coord)
If you don't need access to the key (assigned to square_id
in the above loop), then just use for nested_list in coordinates.values():
.
Upvotes: 1
Reputation: 3612
import json
saved_coordinates = []
with open('data.json','r') as json_file:
coordinates = json.load(json_file)
for obj in coordinates:
for key in obj.keys():
for cords_list in obj[key]:
for index, cords in cords_list.items():
saved_coordinates.append(cords)
print('index: ' + index + '\ncoordinates: ' + str(cords) + '\n')
print(saved_coordinates)
Output:
index: x4, y4
coordinates: [[793, 303]]
index: x3, y3
coordinates: [[793, 367]]
index: x2, y2
coordinates: [[598, 370]]
index: x1,y1
coordinates: [[598, 326]]
index: x4, y4
coordinates: [[1129, 169]]
index: x3, y3
coordinates: [[1130, 293]]
index: x2, y2
coordinates: [[1005, 308]]
index: x1,y1
coordinates: [[1005, 170]]
[[[793, 303]], [[793, 367]], [[598, 370]], [[598, 326]], [[1129, 169]], [[1130, 293]], [[1005, 308]], [[1005, 170]]]
Upvotes: 1