所以我有一个包含4个正方形坐标的JSON文件。 JSON树从正方形ID的索引(1、2、3等)开始,在每个ID中,我们有4组坐标(x1,y1等)。我的最终目标是要建立一个坐标数组,但是,我无法访问标有(x1,y1)坐标的键,并且不确定执行错误吗?任何帮助将不胜感激
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
]
]
}
]
}
]
运行上面的代码时产生此错误:
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
答案 0 :(得分:1)
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)
输出:
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]]]
答案 1 :(得分:1)
您正在将整数传递给仅具有字符串键的字典。 0
与"0"
不同,您的样本数据甚至没有"0"
键(仅存在"1"
和"2"
)。
不生成整数。只需遍历字典的值或项目即可:
for square_id, nested_list in coordinates.items():
for coord in nested_list[0]['x1,y1']:
print("ID:", square_id)
print("Coordinate:", coord)
如果不需要访问密钥(在上述循环中分配给square_id
),则只需使用for nested_list in coordinates.values():
。