我在这里面临一个问题,因为我必须收到一个json,它包含一个字符串和另一个json中某些数据的路径。如何让json路径返回给定一个字符串?
其中包含一些数据
json1 = { "Items": [{ "building": "buildingA", "y": [1, 2, 3], "yl": "A,B,C", "xl": "Data", "x": [1, 2, 3] }, { "y": [4, 5, 6], "x": [1, 2, 3], "predio": "BuildingB", "yl": "D,E,F", "xl": "Data" }] }
和含有所需值的路径中的JSON的JSON:
json2 = { "y": "y//1", }
我试图使此代码解决问题:
def size2(a,i):
x=a.split('//')
y=len(x)
if y ==1:
return i[x[0]]
elif y==2:
return i[x[0]][x[1]]
elif y==3:
return i[x[0]][x[1]][x[2]]
y=json2['y']
for i in json1['Items']:
print(i['y'][1]) #this way works
print(size2(y,i)) #this way fails
的错误信息是:
TypeERROR: list indices must be integers, not str
有谁知道如何解决这个问题?
是的。使用整数标记而不是字符串。 –
非讽刺性的实际帮助:当您执行列表访问时,它将返回JSON数据中的成员,该成员是* string *,然后尝试用于后续索引访问,这会引发错误。将结果转换为int:'int(x [1])'。 –