首页 > python解析中文json插入数据库错误

python解析中文json插入数据库错误

这是需要解析的json文件内容。
{
"datasources": [
{
"datasource": "http://xxx",
"group_type": "xxx",
"label": "\u65e5\u5e38\u4e2d\u5fc3"
}
]
}

这里采用python来解析这个文本内容如下:

#!/usr/bin/env python
#encoding: utf-8

import json
from db import db
import sys

def run():
    db = db()
    with open("cluster_info.txt") as f:
        data = json.load(f)
    print data
    conn = db.connect()
    db.execute(conn, "set names utf-8;")
    for d in data["datasources"]:
        datasource = d["datasource"]
        group_type = d["group_type"]
        label = d["label"]
        sql = "insert into t1 (`c1`, `c2`, `c3`) values ('%s', '%s', '%s')" %\
            (datasource, group_type, label)
        db.execute(conn, sql)
    db.disconnect(conn)

if __name__ == "__main__":
    run()

但是在解析的过程中始终无法把数据插入到数据库中,报的错误如下:

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 151-154: ordinal not in range(256)

自己尝试过各种编码解码,始终没能够解决这个乱码问题。


首先尝试一下还原现场,看一下执行db.execute之前关键变量的值,

In [46]: dic
Out[46]: 
{u'datasources': [{u'datasource': u'http://xxx',
   u'group_type': u'xxx',
   u'label': u'\u65e5\u5e38\u4e2d\u5fc3'}]}

In [47]: dic['datasources'][0]['label']
Out[47]: u'\u65e5\u5e38\u4e2d\u5fc3'

所以,需要向数据库中加数据前,先将label字符串encode为相应的编码吧。(因为别的值只是字母字符串,所以不会报错。)

【热门文章】
【热门文章】