我正在尝试编写一个Python脚本来从JSON文件中读取数据,对其进行一些计算,然后将输出写入一个新的JSON文件。但是我似乎不能自动化JSON读取过程。我得到了这个错误。你能帮我解决这个问题吗?非常感谢
print([a[0]][b[1]][c[1]])
TypeError: list indices must be integers or slices, not strtest.json
{
"male": {
"jack": {
"id": "001",
"telephone": "+31 2225 345",
"address": "10 Street, Aukland",
"balance": "1500"
},
"john": {
"id": "002",
"telephone": "+31 6542 365",
"address": "Main street, Hanota",
"balance": "2500"
}
},
"female": {
"kay": {
"id": "00",
"telephone": "+31 6542 365",
"address": "Main street, Kiro",
"balance": "500"
}
}
}test.py
with open("q.json") as datafile:
data = json.load(datafile)
a = ['male', 'female']
b = ['jack', 'john', 'kay']
c = ['id', 'telephone', 'address', 'balance']
print([a[1]][b[1]][c[1]])发布于 2019-03-06 14:54:12
如果我没理解错的话,您真的希望打印来自JSON的数据,而不是您的中间数组。
所以:
print(data['Male']) # will print the entire Male subsection
print(data['Male']['Jack']) # will print the entire Jack record
print(data['Male']['Jack']['telephone']) # will print Jack's telephone但是为了把它和你的中间数组联系起来:
print(data[a[0]]) # will print the entire Male subsection
print(data[a[0]][b[0]]) # will print the entire Jack record
print(data[a[0]][b[0]][c[0]]) # will print Jack's telephone假设您正确地声明了a:
a = ['Male', 'Female'] # Notice the capitals发布于 2019-03-06 14:51:50
我不知道如何在代码中访问data,因为您直接将硬编码值写入a、b和c。此外,您还可以通过以下方式打印测试:print(a[1], b[1], c[1])。
https://stackoverflow.com/questions/55017135
复制相似问题