Python TypeError与用于迭代数据值的逻辑
让Python TypeError与用于迭代数据值的逻辑,python,python-3.x,dictionary,typeerror,Python,Python 3.x,Dictionary,Typeerror,让json.load()函数的for循环读取“alarmst”字段并返回其值时遇到问题 我在问题代码上面有一个工作代码,它可以很好地处理相同的数据,得到“tag”字段数据值 我认为这可能与dataStatus和dataStart使用分号对数据进行时间格式化有关,即(2015-12-10T05:59:03Z),因此我不确定在运行writerow()函数之前如何解析或替换循环中的值中的字符,或者,如果有人知道一种更好的方法来告诉它,这些特定字段的值的数据类型是Date或类似于Python的显式类型
json.load()
函数的for
循环读取“alarmst”字段并返回其值时遇到问题
我在问题代码上面有一个工作代码,它可以很好地处理相同的数据,得到“tag”字段数据值
我认为这可能与dataStatus
和dataStart
使用分号对数据进行时间格式化有关,即(2015-12-10T05:59:03Z
),因此我不确定在运行writerow()
函数之前如何解析或替换循环中的值中的字符,或者,如果有人知道一种更好的方法来告诉它,这些特定字段的值的数据类型是Date
或类似于Python的显式类型
无附加“alarmst”循环和日期格式数据的工作代码
错误代码
错误
样本数据
你的问题是:
for alarm in tag["alarmst"]:
csv_file.writerow(alarm['dateStatus'],alarm['dateStart'], ...)
请注意,在您的数据中,alarmst
的值是一个JSON对象,它在python中被翻译成字典。因此,当您在其上迭代时,您将得到以下键:报警
将是“dateStatus”、“dateStart”、“status”、…
替换为:
alarm = tag["alarmst"]
csv_file.writerow(...)
您可以发布json数据的示例吗?错误告诉您,
报警
是一个字符串,而不是dict。您的数据不是有效的JSON文件。@kindall我同意。。。这只是一个有效JSON数据的样本,与我遇到的问题部分有关。幸运的是,这个示例似乎为解决我的问题的答案画出了一幅图画。@ITSolutions因此向它传递一个列表,例如csv_文件.writerow([alarm['dateStatus],alarm['dateStart],alarm['status',],alarm['type']])
@ITSolutions我的注释中的代码将一个参数传递给csv_文件。writerow
:列表[alarm['dateStatus']、报警['dateStart']、报警['status']、报警['type']]
。您的代码传递两个参数:字符串报警['dateStatus']
和列表[alarm['dateStart']、报警['status']、报警['type']]
。
csv_file.writerow(alarm['dateStatus'], [alarm['dateStart'], alarm['status'], alarm['type']])
TypeError: string indices must be integers
{
"success": true,
"moreDataAvailable": true,
"devs": [
{
"id": 111111,
"name": "dev123",
"tags": [
{
"id": 10100,
"name": "CleanTask",
"dataType": "Bool",
"description": "",
"alarmHint": "",
"value": 0,
"quality": "good",
"alarmst": {
"dateStatus": "2016-11-08T06:58:06Z",
"dateStart": "2016-11-08T06:22:16Z",
"status": "RTN",
"type": "None"
},
for alarm in tag["alarmst"]:
csv_file.writerow(alarm['dateStatus'],alarm['dateStart'], ...)
alarm = tag["alarmst"]
csv_file.writerow(...)