Python TypeError with for logic iterating data values -


i'm having problem getting for loop of json.load() function read through "alarmst" fields , bring values.

i have working code above problem code works fine same data getting "tag" field data values fine.

i think may related datastatus , datastart having time formatted data semicolons i.e. (2015-12-10t05:59:03z) i'm not sure how parse out or replace characters in values in loop before running through writerow() function, or if knows of better way tell data type of value of specific fields date or explicit python.

working code without additional "alarmst" loop , date formatted data

import json import csv  open('c:\\folder\\dev\\tags.txt',"r") file:     data = json.load(file)  open('c:\\folder\\dev\\tags.csv',"w",newline='') file:      csv_file = csv.writer(file)     dev in data["devs"]:         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 error

import json import csv  open('c:\\folder\\dev\\tagalarms.txt',"r") file:     data = json.load(file)  open('c:\\folder\\dev\\tagalarms.csv',"w",newline='') file:     csv_file = csv.writer(file)     dev in data["devs"]:         tag in dev["tags"]:             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 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"           }, 

your issue line:

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

notice in data, value alarmst json object, in python translated dictionary. when iterate on it, end keys: i.e. alarm "datestatus", "datestart", "status", ....

replace with:

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

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -