Fetch json value correctly and convert into integers using python3 and upload directly into database but in python code there is some error generated

Viewed 32

In this code I want to fetch JSON value from https://thingspeak.com/channels/1441388/feed.json of field1 and field2 and upload into my local database using python3 but the error comes out in "first" variable that "TypeError: string indices must be integers".

import urllib.request
import json
import mysql.connector
url = "https://thingspeak.com/channels/1441388/feed.json"
mydb=mysql.connector.connect(host="localhost",user="root",passwd="123",database="path")

with urllib.request.urlopen(url) as url:
    s=url.read()
data = json.dumps(s.decode("utf-8"))
N=10
for num in reversed(range(N + 1)) :   # fetch last ten data 
    first = (data['feeds'][num]['field1'])  # fetch field1 data from JSON
    print("first",first)
    second = data['feeds'][num]['field2']
    print("second",second)
    cursor = mydb.cursor()
    insert_stmt = ("INSERT INTO details(Distance,water_level,Connected_device)"
       "VALUES (%s, %s, %s)")    
    data = (first,second,'Arduino & GPRS')
    
    try:
        cursor.execute(insert_stmt, data)
        mydb.commit()
        #cursor.close()
        print(cursor.rowcount, "record inserted.")
    except:
        mydb.rollback()

**I get this output
**

**Traceback (most recent call last):
  File "D:\IOT\Blind Stick\fetch.py", line 14, in <module>
    first = list(data['feeds'][num]['field1'])
TypeError: string indices must be integers**

So I am wondering what wrong I am doing here?

1 Answers
Related