python中json和字符编码的转换

背景

json是用来转换python object 和json format 的,字符编码有gb2312,gb18030/gbk,utf-8等。

在 Python 中出现的 str 都是用字符集编码的 ansi 字符串。Python 本身并不知道 str 的编码,需要由开发者指定正确的字符集 decode。

原理分析

因为 Python 认为 16 位的 unicode 才是字符的唯一内码,而大家常用的字符集如 gb2312,gb18030/gbk,utf-8,以及 ascii 都是字符的二进制(字节)编码形式。把字符从 unicode 转换成二进制编码,当然是要 encode。

# 从 str 转换成 unicode  

print s.decode('utf-8')

# 从 unicode 转换成 str    

print u.encode('utf-8'

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

  • json.dump(objfpskipkeys=Falseensure_ascii=Truecheck_circular=Trueallow_nan=Truecls=Noneindent=None,separators=Noneencoding="utf-8"default=Nonesort_keys=False**kw)

  • Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.

  • json.dumps(objskipkeys=Falseensure_ascii=Truecheck_circular=Trueallow_nan=Truecls=Noneindent=None,separators=Noneencoding="utf-8"default=Nonesort_keys=False**kw)

  • Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.

  • json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[,**kw]]]]]]]])

  • Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using thisconversion table.

  • json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[,**kw]]]]]]]])

  • Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

 

json有上面四种function,注意带s和不带s的区别,json.dumps是把python object转换为json format,反之,json.loads是把json str 转换为python object。

python object 有dict , list 等。

实例讲解

下面给出输出一个大的json字符串到文件,并以可读的格式输出。

#!/usr/bin/env python

import urllib2

import json

import sys

url = 'world.taobao.com/search/json.htm'

url = 'http://' + url

keyword = sys.argv[1]

url = url + '?q=' + keyword

print url

request = urllib2.Request(url)

response = urllib2.urlopen(request)

content = response.read()

if isinstance(content, basestring):

        print "content is string"

else:

        print "content is not string"

content = json.loads(content, encoding='gbk')

content = json.dumps(content, encoding='gbk', ensure_ascii=False, indent=4, separators=(',', ': '))

content = content.encode('utf-8')

file = keyword

f = open(file, 'w')

f.write(content)

f.close()

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值