2017. 3. 31.

python3에서 sqlite3의 한글이 들어간 text field의 처리

sqlite3에서 필드가 text type일 때, 한글이 들어가 있지 않으면, 타입이 스트링이고, 들어가 있는 경우는 bytes가 된다. 그래서, json text를 가져와서 처리 하려고 하는 경우, json.loads는 str 타입만 받아 드리기 때문에 꺼내온 데이터의 타입을 체크하고, str 타입이 아니면 변환이 필요 하다.

def get_str( obj ):
    final_str = ""
    if type(obj) is bytes:
        final_str = obj.decode()
    else:
        final_str = obj

# select  obj from my_table. -- obj is text type.
sql = 'select obj from my_table'
sql_conn.execute( sql)
row = sql_conn.fetchone()
obj = row[0]
obj_json = json.loads( get_str( obj))

댓글 없음:

댓글 쓰기