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()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章