Home > database >  Trying construc JSON file but got error concat datetime to string
Trying construc JSON file but got error concat datetime to string

Time:11-13

I don't have much experience with python, I'm trying to run a query in the database where it returns me the fields of number, status, opening date, expiration date and description, but I'm getting an error even while encoding, below is my code, could they help me with what I'm doing wrong

json_requisicoes.append({'Numero Requisicao:' row[0], 'Status:' row[1], 'Data de Abertura:' row[2], 'Prazo:' row[3], 'Descricao:' row[4]})

TypeError: can only concatenate str (not "datetime.datetime") to str

import mysql.connector
import json
from datetime import datetime
import array as arr
    
class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
            return obj.isoformat()
        elif isinstance(obj, datetime.timedelta):
            return (datetime.datetime.min   obj).time().isoformat()
    return super(DateTimeEncoder, self).default(obj)
    
def GetRequisicoes():
    json_requisicoes = []
    select_requisicoes = ("""SELECT * FROM data_req
                             WHERE DATE(sla_due_date_req) <= DATE(NOW()) 
                             AND status_req NOT LIKE 'Pendente'
                             ORDER BY n_req ASC;""")
    cursor = conn.cursor()
    cursor.execute(select_requisicoes)
    result = cursor.fetchall()
        
    for row in result:
        json_requisicoes.append({'Numero Requisicao:' row[0], 'Status:' row[1], 'Data de Abertura:' row[2], 'Prazo:' row[3], 'Descricao:' row[4]})
    with open("./output_requisicoes.json", 'w', encoding='utf-8') as f:
        json.dump(json_requisicoes, f, ensure_ascii=False, indent=4, cls=DateTimeEncoder) 
    cursor.close() 

CodePudding user response:

You shouldn't be concatenating strings. You should be appending dictionaries. Dictionaries have : between the keys and values, not .

You also need to format the datetime as a string, because raw datetime objects can't be represented in JSON. You can use the isoformat() method for this.

    for row in result:
        json_requisicoes.append({
            'Numero Requisicao': row[0], 
            'Status': row[1], 
            'Data de Abertura': row[2].isoformat(),
            'Prazo': row[3], 
            'Descricao': row[4]
    })
  • Related