1. 程式人生 > >python3 json模塊

python3 json模塊

span div encoding 結果 轉化 粉絲 pen style 字符

import json

‘‘‘把python對象轉化為json串(字符串), ensure_ascii處理中文亂碼‘‘‘
dic = {"復聯4": "好看嗎", "身邊": "粉絲", "蔡徐坤": None, "坤坤": True, "段坤": False}
s = json.dumps(dic, ensure_ascii=False)
print(s)
print(type(s))

執行結果:
{"坤坤": true, "身邊": "粉絲", "蔡徐坤": null, "復聯4": "好看嗎", "段坤": false}
<class ‘str‘>

‘‘‘把python對象轉化為json字符串並寫入文件‘‘‘
json.dump(dic, open("info.json", mode="w", encoding="utf-8"))

執行結果:
info.json文件內容:
{"\u5764\u5764": true, "\u8eab\u8fb9": "\u7c89\u4e1d", "\u8521\u5f90\u5764": null, "\u590d\u80544": "\u597d\u770b\u5417", "\u6bb5\u5764": false}


‘‘‘將json字符串轉化為字典‘‘‘
s = ‘{"復聯4": "好看嗎", "身邊": "粉絲", "蔡徐坤": null, "坤坤": true, "段坤": false}‘
dic = json.loads(s)
print(dic)
print(type(dic))

執行結果:
{‘坤坤‘: True, ‘身邊‘: ‘粉絲‘, ‘蔡徐坤‘: None, ‘復聯4‘: ‘好看嗎‘, ‘段坤‘: False}
<class ‘dict‘>

‘‘‘從文件中讀取json字符串,轉化為字典‘‘‘
dic2 = json.load(open("info.json", mode="r"))
print(dic2)
print(type(dic2))

執行結果:
{‘坤坤‘: True, ‘身邊‘: ‘粉絲‘, ‘蔡徐坤‘: None, ‘復聯4‘: ‘好看嗎‘, ‘段坤‘: False}
<class ‘dict‘>

‘‘‘將字符串編碼為bytes‘‘‘
print("荊防顆粒dsjaklf".encode("utf-8"))

執行結果:
b‘\xe8\x8d\x86\xe9\x98\xb2\xe9\xa2\x97\xe7\xb2\x92dsjaklf‘

python3 json模塊