我在这里面临一个问题,因为我必须接收一个 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:
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
有人知道如何解决这个问题吗?
最佳答案
您可以这样做,假设由所有数字字符组成的任何路径组件都是整数序列索引:
def size2(y, i):
obj = i
for comp in ((int(z) if z.isdigit() else z) for z in y.split('//')):
obj = obj[comp]
return obj
y = json2['y']
for i in json1['Items']:
print(size2(y, i)) # this way now works
通过使用内置的 reduce()
可以使 size2()
函数更加简洁。功能:
def size2(y, i):
return reduce(lambda obj, v: obj[int(v) if v.isdigit() else v], y.split('//'), i)
关于python - 给定一个字符串,如何返回 json 路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251567/