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
(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None,separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)Serialize obj as a JSON formatted stream to fp (a
.write()
-supporting file-like object) using this conversion table.
json.
dumps
(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None,separators=None, encoding="utf-8", default=None, sort_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 aunicode
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
orunicode
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()
相关文章