Below is my code that I use for inserting a json into my database
list=result['intervalsDataPoints']
for item in list:
if item['dataPoints'] !=[]:
result=item['dataPoints']
#print(result)
#print('hello')
for element in result:
dt = datetime.datetime.now()
#element["dt"] = dt
#element["epic"]=epic
#print(element)
#print(element['openPrice']['bid'])
print(element['timestamp'])
date_timestamp = datetime.datetime.fromtimestamp(element['timestamp']/1000)
cursor.execute("""INSERT INTO market_data_historic VALUES('%s','%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT ON CONSTRAINT UNIQUE_history DO NOTHING"""%(dt,epics,date_timestamp,element['openPrice']['bid'],element['openPrice']['ask'],element['closePrice']['bid'],element['closePrice']['ask'],element['highPrice']['bid'],element['highPrice']['ask'],element['lowPrice']['bid'],element['lowPrice']['ask'],element['lastTradedVolume']))
#cursor.executemany("""INSERT INTO market_data_historic(created_at,epic,timestamp,openprice_bid,openprice_close,closeprice_bid,closeprice_ask,highprice_bid,highprice_ask,lowprice_bid,lowprice_ask,last_traded_volume) VALUES (%(dt)s,%(epic)s,%(timestamp)s,%(openPrice['bid'])s,%(openPrice['close'])s,%(closePrice['bid'])s,%(closePrice['ask'])s,%(highPrice['bid'])s,%(highPrice['ask'])s,%(lowPrice['bid'])s,%(lowPrice['ask'])s,%(lastTradedVolume)s);""",element)
conn.commit()
#print(item)
However, some of the items may be NULL which causes my insert statement to break causing this error:
cursor.execute("""INSERT INTO market_data_historic VALUES('%s','%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT ON CONSTRAINT UNIQUE_history DO NOTHING"""%(dt,epics,date_timestamp,element['openPrice']['bid'],element['openPrice']['ask'],element['closePrice']['bid'],element['closePrice']['ask'],element['highPrice']['bid'],element['highPrice']['ask'],element['lowPrice']['bid'],element['lowPrice']['ask'],element['lastTradedVolume']))
KeyError: 'bid'
I have tried appending or NONE to the end of each element making the query like this:
cursor.execute("""INSERT INTO market_data_historic VALUES('%s','%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT ON CONSTRAINT UNIQUE_history DO NOTHING"""%(dt,epics,date_timestamp,element['openPrice']['bid'] or None,element['openPrice']['ask'] or None,element['closePrice']['bid'] or None,element['closePrice']['ask'] or None,element['highPrice']['bid'] or None,element['highPrice']['ask'] or None,element['lowPrice']['bid'] or None,element['lowPrice']['ask'] or None,element['lastTradedVolume'] or None))
Still no luck! How do you guys suggest I go about accounting for NONE/NULL values in my code above