我在這裏面臨一個問題,因爲我必須收到一個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])'。 –