1. 程式人生 > >Python學習---JSON補充內容[中文編碼 + dumps解析]

Python學習---JSON補充內容[中文編碼 + dumps解析]

src tom lba 占位符 display https one encoder none

JSON補充內容[微信解決中文亂碼,接上]

import json

# 英文顯示
dic = {"hello": "world"}
str = json.dumps(dic)
# type(str) <class ‘str‘> str: {"hello": "world"}
print("type(str)", type(str), ‘str:‘, str)

# 中文顯示
r = {"key": "中國"}
st = json.dumps(r)  # 序列化後變成字符串,中文變成ascii編碼
# type(st) <class ‘str‘> st: {"key": "\u4e2d\u56fd"}
print("type(st)", type(st), ‘st:‘, st)

# 中文bytes處理
b = bytes(st, encoding="utf-8")
# type(b): <class ‘bytes‘> b: b‘{"key": "\\u4e2d\\u56fd"}‘  # 發送utf-8字節給微信服務器
print("type(b):",type(b), "b:", b)

# 解決方案一: 不使用ensure_ascill編碼
k = {"key": "中國"}
new = json.dumps(k, ensure_ascii=False)
print(new)   # {"key": "中國"}
bb = bytes(new, encoding="utf-8")
print(bb)  # b‘{"key": "\xe4\xb8\xad\xe5\x9b\xbd"}‘

# 解決方案二:先對字典中的msg信息進行占位符處理,然後進行json.dumps[此時是字符串了],接著利用占位符傳入msg信息
l = {"key": ‘%(msg)s‘ }  # 註意引號
new1 = json.dumps(l)
print(new1)  # {"key": "%(msg)s"}
new1 = new1 %{‘msg‘: ‘中國‘}
print(new1)  # {"key": "中國"}
pp = bytes(new, encoding="utf-8")
print(pp)  # b‘{"key": "\xe4\xb8\xad\xe5\x9b\xbd"}‘
‘‘‘
總述:
    問題定位:
        json.dumps()將中文進行了Ascii編碼[默認編碼]後返回編碼後的字符串【\u4e2d\u56fd】
        bytes()將字符串轉變為字節進行發送【\\u4e2d\\u56fd】
           微信接到消息後進行字節byte向字符串str轉換,然後發送給前臺。即【\\u4e2d\\u56fd】 --》【\u4e2d\u56fd】 --》亂碼
    問題解決:
        1. 不使用ASCII編碼,則直接返回中文後進行字節編碼  json.dumps(k, ensure_ascii=False)
        2. 使用占位符,在json.dumps()後傳入msg信息進去  j = j %{"msg": msg} -->此時顯示中文
‘‘‘

技術分享圖片

Json.dumps(cls參數內容以及轉換規則)

if cls is None:
    cls = JSONEncoder

+-------------------+---------------+
| Python            | JSON          |
+===================+===============+
| dict              | object        |
+-------------------+---------------+
| list, tuple       | array         |
+-------------------+---------------+
| str               | string        |
+-------------------+---------------+
| int, float        | number        |
+-------------------+---------------+
| True              | true          |
+-------------------+---------------+
| False             | false         |
+-------------------+---------------+
| None              | null          |
+-------------------+---------------+

Python學習---JSON補充內容[中文編碼 + dumps解析]