JSON + Python 'utf8' codec can not decode byte 0xba in position 7:

1

Dear I want to save information in a json file but it tells me this error:

Traceback (most recent call last):
  File "interbasecom.py", line 271, in <module>
    classPresupuesto.getPresupuestos()
  File "interbasecom.py", line 268, in getPresupuestos
    json.dump(rowarray_list_two, fileInetrbase, cls=DecimalEncoder,default=date_handler, ensure_ascii = False)
  File "C:\Python27\lib\json\__init__.py", line 181, in dump
    for chunk in iterable:
  File "C:\Python27\lib\site-packages\simplejson\encoder.py", line 665, in _iterencode
    for chunk in _iterencode_list(o, _current_indent_level):
  File "C:\Python27\lib\site-packages\simplejson\encoder.py", line 515, in _iterencode_list
    for chunk in chunks:
  File "C:\Python27\lib\site-packages\simplejson\encoder.py", line 602, in _iterencode_dict
    yield _encoder(value)
  File "C:\Python27\lib\site-packages\simplejson\encoder.py", line 61, in encode_basestring
    s = s.decode('utf-8')
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xba in position 7: invalid start byte

Here I pass the complete script of the python file that I run so that the json generates me.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import kinterbasdb
import os
import sys
import MySQLdb
import datetime
import time
from os.path import exists
import time
from threading import Timer
import shutil
import string
from connections import *
import json
from decimal import *
from pprint import pprint
import decimal, simplejson


def date_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    else:
        raise TypeError



class DecimalEncoder(simplejson.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        return super(DecimalEncoder, self).default(o)




class InterbaseCom(DecimalEncoder):

    def decimal_default(obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        else:

            raise TypeError



    def getPresupuestos(self):

        connectionsCls = Connections()
        #conexion con firebird
        conGDB = connectionsCls.interbase
        #conexion con mysql
        conMysql = connectionsCls.dbMysql


        rowarray_list = []

        sqlSelect_account = """ Call SELECT_ACCOUNT()"""
        cursorSelect_account= conMysql.cursor()
        cursorSelect_account.execute(sqlSelect_account)
        for cuenta in cursorSelect_account:
            clienteId = cuenta[0]
            descripcionId=cuenta[1]

            clientes ={
                "Cuentas":{
                "ClientID":clienteId,
                "ClientDescri":descripcionId
                    }}





            rowarray_list.append(clientes)
        with open('cuentasMysql.json', 'w') as file:
            json.dump(rowarray_list, file, encoding='latin1')

        #leer = json.loads(open('cuentasMysql.json').read())


        with open('cuentasMysql.json') as data_file:

             data = json.load(data_file)
             for fileread in data:   

                #pprint(fileread['Cuentas']['ClientID'])

                sqlVecomproPresu = """SELECT 
                    *
                FROM
                    EMPRESAFST(null,null, null,
                    null, null, null, null, null,
                    null, null,null,null,null,
                    null, null, null, '%s', '%s',
                    null, null, null,null, null,
                    null,null, null,null,
                    null, '1', null,null,null,
                    null,null)"""%(fileread['Cuentas']['ClientID'],fileread['Cuentas']['ClientID'])

                cursorSelect_Interbase= conGDB.cursor()
                cursorSelect_Interbase.execute(sqlVecomproPresu)

                for cuentasInetrbase in cursorSelect_Interbase:
                        rowarray_list_two=[]
                        vecompropresuInterbase=[]
                        vecompropresuInterbase = {
                                "CLIENTE":cuentasInetrbase[0],
                                "CLI": cuentasInetrbase[1],
                                "DE": cuentasInetrbase[2],
                                "AG": cuentasInetrbase[3],
                                "DES":cuentasInetrbase[4],

                                                                    }






                        rowarray_list_two.append(vecompropresuInterbase)
                        with open('cuentasInterbase.json','w') as fileInetrbase:
                            json.dump(rowarray_list_two, fileInetrbase, cls=DecimalEncoder,default=date_handler, ensure_ascii = False)
t0 = time.clock()
classPresupuesto = InterbaseCom()
classPresupuesto.getPresupuestos()
print "%.2f sec" % (time.clock() - t0)
    
asked by Nahuel Jakobson 26.07.2017 в 14:42
source

1 answer

1

The solution was to place the same encoding on the other json

   rowarray_list_two.append(vecompropresuInterbase)
                        with open('cuentasInterbase.json','w') as fileInetrbase:
                            json.dump(rowarray_list_two, fileInetrbase, cls=DecimalEncoder,default=date_handler, encoding="latin1")
    
answered by 26.07.2017 в 17:13