我正在解析来自 fitbit API (https://dev.fitbit.com/build/reference/web-api/heart-rate/) 的数据 并不断收到 TypeError: 字符串索引必须是整数。根据阅读其他问题,我了解到这可能是由于处理字典列表所致。现在,我正在像这样解析我的 json:
fat_burn = "{0:.2f}".format(activity_request.json()['activities-heart'][0]['value']['heartRateZones'][1]['minutes'])
我的 json 看起来像这样:
{
"activities-heart": [
{
"dateTime": "2015-08-04",
"value": {
"customHeartRateZones": [],
"heartRateZones": [
{
"caloriesOut": 740.15264,
"max": 94,
"min": 30,
"minutes": 593,
"name": "Out of Range"
},
{
"caloriesOut": 249.66204,
"max": 132,
"min": 94,
"minutes": 46,
"name": "Fat Burn"
},
{
"caloriesOut": 0,
"max": 160,
"min": 132,
"minutes": 0,
"name": "Cardio"
},
{
"caloriesOut": 0,
"max": 220,
"min": 160,
"minutes": 0,
"name": "Peak"
}
],
"restingHeartRate": 68
}
}
]
}
我在解析 json 时遇到了一个类似于 TypeError 的错误:列表索引必须是整数或切片,而不是 str 如下:
fat_burn = "{0:.2f}".format(activity_request.json()['activities-heart']['value']['heartRateZones'][1]['minutes'])
但设法通过添加 [0] 来解决它。
为什么我需要索引第一个条目来解决该错误,我需要做什么来解决我现在遇到的错误?
答案 0 :(得分:0)
activities-heart
是一个键,其值是一个列表。列表是连续的,并以整数(例如,0、1、2、...)作为索引。
在您的表达式中,您正在尝试使用字符串(值)在列表中执行查找。这是您的 TypeError
的来源。
数据中的其他元素,例如 this..
{
"caloriesOut": 740.15264,
"max": 94,
"min": 30,
"minutes": 593,
"name": "Out of Range"
}
Are dictionaries which allow you to use any hashable values for the key. This is why you're able to use a string for the key.
https://www.geeksforgeeks.org/difference-between-list-and-dictionary-in-python
答案 1 :(得分:0)
看,让我们将您的数据存储在一个变量 a 中,然后,
当你这样做时,a['activities-heart']:
你会得到这样的输出:
[email]="true"
这是一个列表,0 索引是您的价值,因此,
[{'dateTime': '2015-08-04',
'value': {'customHeartRateZones': [],
'heartRateZones': [{'caloriesOut': 740.15264,
'max': 94,
'min': 30,
'minutes': 593,
'name': 'Out of Range'},
{'caloriesOut': 249.66204,
'max': 132,
'min': 94,
'minutes': 46,
'name': 'Fat Burn'},
{'caloriesOut': 0, 'max': 160, 'min': 132, 'minutes': 0, 'name': 'Cardio'},
{'caloriesOut': 0, 'max': 220, 'min': 160, 'minutes': 0, 'name': 'Peak'}],
'restingHeartRate': 68}}]
会给你一本字典。
因此您可以这样执行:
a['activities-heart'][0]
输出:
a['activities-heart'][0]['value']['heartRateZones'][1]['minutes']