IT Solutions IT Solutions - 1 year ago 76
Python Question

Python TypeError with for logic iterating data values

I'm having a problem getting the

loop of the
function to read through the "alarmst" fields and bring back their values.

I have working code above the problem code that works fine with the same data getting the "tag" field data values just fine.

I think it may be related to the
having time formatted data with semicolons i.e. (
) so I'm not sure how to parse those out or replace characters in the values in the loop before running through the
function, or if someone knows of a better way to tell it that the data type of the value of those specific fields is
or something explicit like that with Python.

Working Code without additional "alarmst" loop and Date formatted data

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']])

Trouble Code with the error

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']])

The Error

csv_file.writerow(alarm['dateStatus'], [alarm['dateStart'], alarm['status'], alarm['type']])
TypeError: string indices must be integers

Sample Data

"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"

Answer Source

Your issue is the line:

for alarm in tag["alarmst"]:
    csv_file.writerow(alarm['dateStatus'],alarm['dateStart'], ...)

Notice that in your data, the value for alarmst is a JSON object, which in python is translated into a dictionary. So when you iterate over it, you end up with the keys: i.e. alarm will be "dateStatus", "dateStart", "status", ....

Replace it with:

alarm = tag["alarmst"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download