python 保持json数据到本地时的编码

来源:互联网 发布:linux创建用户名和密码 编辑:程序博客网 时间:2024/05/05 07:45
import requestsimport jsondef getAndSaveJSON():    query_url = 'http://fanyi.youdao.com/openapi.do?' \      'keyfrom=tinxing&key=1312427901&type=data&doctype=json&version=1.1&q=logging'    jsStr = json.loads(requests.get(query_url).text)    f = open("./jsondatafile.json", "a")  # a:附加写方式打开,不可读    a = json.dumps(jsStr, ensure_ascii=False)    print type(a)    f.write(a)    f.close()    print 'success'

Traceback (most recent call last):UnicodeEncodeError: 'ascii' codec can't encode characters in position 54-57: ordinal not in range(128)

json数据获取并保存到本地时,出现了编码问题,试了很多方法最后看了

引用块内容
http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20
将代码修改下
a = json.dumps(jsStr, ensure_ascii=False).encode("utf-8")
问题解决

第二种方法
原来用open方法打开会有一些问题。open打开文件只能写入str类型,不管字符串是什么编码方式

import codecs
f = codecs.open(“./jsondatafile.json”, “a”,”utf-8”)
这种方法可以指定一个编码打开文件,使用这个方法打开的文件读取返回的将是unicode。写入时,如果参数 是unicode,则使用open()时指定的编码进行编码后写入;如果是str,则先根据源代码文件声明的字符编码,解码成unicode后再进行前述 操作。相对内置的open()来说,这个方法比较不容易在编码上出现问题。来源于http://www.cnblogs.com/buptldf/p/4805879.html

json.dumps() 编码:把一个Python对象编码转换成Json字符串
json.loads() 解码:把Json格式字符串解码转换成Python对象

  • decode的作用是将其他编码的字符串转换成unicode编码,
    如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。
  • encode的作用是将unicode编码转换成其他编码的字符串,
    如str2.encode(‘gb2312’),表示将unicode编码的字符串str2转换成gb2312编码。
0 0
原创粉丝点击