python 轉換為json時候 漢字編碼問題
阿新 • • 發佈:2018-12-30
有這樣一個需求:
需要一個json 檔案 資料從資料庫裡查詢出來
1. 設定檔案頭
# -*- coding:utf-8 -*-
2. 連線資料庫 將資料庫連線資料庫的編碼設定為utf8 db = MySQLdb.connect(host='資料庫,user=使用者名稱,passwd=密碼,db='資料庫, init_command="set names utf8" )
3. 查詢出來的資料轉化為json
t = json.dumps(r, ensure_ascii=False)
如果 不加 ensure_ascii=False 輸出的 t 如果有漢字的話都預設給轉換成一堆編碼 如果加上的話 就都能正常顯示變成了漢字不加的話: t = json.dumps(r)
[{"category": {"label": "\u65b0\u8f66"}, "title": "\u5168\u65b0\u8d77\u4e9a\u798f\u745e\u8fea\u8def\u8bd5\u8c0d\u7167\u66dd\u5149 \u6216\u4e3a\u5b9a\u540dK3", "url": "http://auto.sohu.com/20120523/n343878794.shtml", "source": "\u641c\u72d0\u6c7d\u8f66", "time": 1337740004, "imgUrl": ""}, {"category": {"label": "\u65b0\u8f66"}, "title": "\u65b0\u5965\u8feaQ7/Q8\u66f4\u591a\u4fe1\u606f\u66dd\u5149 \u5c06\u57fa\u4e8eMLB\u5e73\u53f0", "url": "http://auto.sohu.com/20120523/n343873150.shtml", "source": "\u641c\u72d0\u6c7d\u8f66", "time": 1337737913, "imgUrl": ""}]
加上的話: t = json.dumps(r, ensure_ascii=False)
[{"category": {"label": "新車"}, "title": "全新起亞福瑞迪路試諜照曝光 或為定名K3", "url": "http://auto.sohu.com/20120523/n343878794.shtml", "source": "汽車", "time": 1337740004, "imgUrl": ""}, {"category": {"label": "新車"}, "title": "新奧迪Q7/Q8更多資訊曝光 將基於MLB平臺", "url": "http://auto.sohu.com/20120523/n343873150.shtml", "source": "汽車", "time": 1337737913, "imgUrl": ""}]
我們在post請求資料時,響應的內容是json資料,但是返回的json資料中文顯示有問題,變成 \uXXX的形式。這是因為中文以 unicode 編碼了,而預設是以ASCII解析的,中文不在ASCII編碼中,所以無法顯示。
這時候我們可以用 import json 然後呼叫json.loads() 和json.dumps()來使中文正確顯示。 下面的程式碼(data是中文不能正常顯示的json串,newjson是處理後中文正常顯示的字串)
import json
myjson=json.loads(data) #data是向 api請求的響應資料,data必須是字串型別的
newjson=json.dumps(myjson,ensure_ascii=False) #ensure_ascii=False 就不會用 ASCII 編碼,中文就可以正常顯示了
print newjson