mysql - python解析中文json插入数据库错误
阿神
阿神 2017-04-17 13:16:59
[Python讨论组]

这是需要解析的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)

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

阿神
阿神

闭关修行中......

全部回复(1)
巴扎黑

首先尝试一下还原现场,看一下执行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为相应的编码吧。(因为别的值只是字母字符串,所以不会报错。)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号