Home > Mobile >  Getting Error Object of type bytes is not JSON serializable in django
Getting Error Object of type bytes is not JSON serializable in django

Time:05-12

I Everyone i my trying to to convert my response to to json its getting error which i have mention in question. how can i convert this response to json as per me problem is Decimal and b(byte), please help me out.

code- excuiting raw sql query and converting to json formet

def s(reqeust):
    car_report= connection.cursor()
    car_report.execute('''select....''')
    car_report_data = car_report.fetchall()
    json_res=[]
    for row in car_report_data:
        json_obj=dict(number=row[0],name=row[1],total_trips=row[2],status=row[3],day1_trips=row[4],day2_trips=row[5],day3_trips=row[6],day4_trips=row[7],day5_trips=row[8],day6_trips=row[9],day7_trips=row[10])
        json_res.append(json_obj)
        print(json_res,'json_res')
    return JsonResponse(json_res,safe=False)

Response.

[{'number': '0001', 'name': 'john', 'total_trips': Decimal('32'), 'status': '', 'day1_trips': b'8', 'day2_trips': b'17', 
 'day3_trips': b'0', 'day4_trips': b'0', 'day5_trips': b'7', 'day6_trips': b'R', 'day7_trips': b'0'}]

CodePudding user response:

The reason for your error is that JSON doesn't understand 'bytes'. So you'd need to convert the bytestring to string.

The following is one way of doing it.

def s(reqeust):
    car_report= connection.cursor()
    car_report.execute('''select....''')
    car_report_data = car_report.fetchall()
    json_res=[]
    for row in car_report_data:
        srow = [x.decode('utf-8') if isinstance(x, bytes) else x for x in row]

        json_obj = dict(number=srow[0],
                        name=srow[1],
                        total_trips=srow[2],
                        status=srow[3],
                        day1_trips=srow[4],
                        day2_trips=srow[5],
                        day3_trips=srow[6],
                        day4_trips=srow[7],
                        day5_trips=srow[8],
                        day6_trips=srow[9],
                        day7_trips=srow[10])
        json_res.append(json_obj)
        print(json_res,'json_res')
    return JsonResponse(json_res,safe=False)
  • Related