I'm having a problem getting the for loop of the json.load() 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 dataStatus and dataStart having time formatted data with semicolons i.e. (2015-12-10T05:59:03Z) so I'm not sure how to parse those out or replace characters in the values in the loop before running through the writerow() function, or if someone knows of a better way to tell it that the data type of the value of those specific fields is Date 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"
},
alarmis a string, not a dict.