我在获取for函数的json.load()循环以读取“ alarmst”字段并恢复其值时遇到问题。

我在问题代码上方有正常工作的代码,该代码可以与相同的数据正常工作,而“ tag”字段数据值也可以正常工作。

我认为这可能与dataStatusdataStart具有带有分号(即(2015-12-10T05:59:03Z))的时间格式化数据有关,因此我不确定在运行之前如何解析这些字符或替换循环中的字符writerow()函数,或者是否有人知道一种更好的方法来告知这些特定字段的值的数据类型为Date或类似Python的显式值。

工作代码,无其他“警报”循环和日期格式的数据

import json
import csv

with open('C:\\folder\\dev\\Tags.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\Tags.csv',"w",newline='') as file:

    csv_file = csv.writer(file)
    for dev in data["devs"]:
        for tag in dev["tags"]:
            csv_file.writerow([tag['id'], tag['name'], tag['dataType'], tag['description'], tag['alarm'], tag['value'], tag['quality'], tag['DevTagId']])


错误代码与错误

import json
import csv

with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
    csv_file = csv.writer(file)
    for dev in data["devs"]:
        for tag in dev["tags"]:
            for alarm in tag["alarmst"]:
                csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['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'], ...)


请注意,在您的数据中,alarmst的值是一个JSON对象,在python中将其转换为字典。因此,当您对其进行迭代时,最终会得到以下密钥:即alarm将为"dateStatus", "dateStart", "status", ...

替换为:

alarm = tag["alarmst"]
csv_file.writerow(...)

关于python - 带有逻辑迭代数据值的Python TypeError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40535615/

10-13 07:15
查看更多