python json模組小技巧

2022-07-21 18:48:14 字數 1369 閱讀 8479

python的json模組通常用於與序列化資料,如

def get_user_info(user_id):

res =

json_str = json.dumps(res)

return json_str

但是當要序列化的資料裡面包含中文字元時,會變成這樣

import json

res =

print(json.dumps(res))

#

解決辦法: 在json.dumps()裡面加入乙個引數ensure_ascii=false

import json

res =

print(json.dumps(res))

#

這裡有乙個問題,如果json的結構很複雜,輸出的結果就會很亂,不清晰,這是可以加入乙個引數使其格式化

import json

res =

print(json.dumps(res))

#

如果序列化的資料裡面有python的datetime.datetime型別,那麼序列化會報錯

import datetime

res =

print(json.dumps(res, ensure_ascii=false, indent=4))

#typeerror: datetime.datetime(2019, 11, 3, 19, 8, 45, 987000) is not json serializable

解決辦法是使用自定義的jsonencoder代替原生的jsonencoder

class datetimeencoder(json.jsonencoder):

def default(self, obj):

if isinstance(obj, datetime.datetime):

return obj.strftime('%y-%m-%d %h:%m:%s')

elif isinstance(obj, datetime.date):

return obj.strftime('%y-%m-%d')

else:

return json.jsonencoder.default(self, obj)

res =

print(json.dumps(res, ensure_ascii=false, indent=4, cls=datetimeencoder))

#

python json模組學習

filename username.json try with open filename as file obj username json.load file obj except filenotfounderror username input 請輸入使用者名稱 with open filen...

python JSON模組使用

最近在使用有道api翻譯的時候發現,json處理字典資料的時候出現問題,因此想要學習一下json的用法 json.loads import json 用於將python的資料轉化為json的資料形式,語法json.dumps obj,skipkeys false ensure ascii true ...

python json模組使用示例

1 簡介 json 標準化 序列化 的資料格式,幾乎所有語言都支援的一種資料介面格式,在python中,json可以方便地用來序列化常規的資料型別 字典,集合,列表等 也可以序列化類的例項等,但比較麻煩。json序列化後的資料,可讀性好,人能夠識別。2 序列化到記憶體物件 及 從記憶體反序列化的兩種...