Python?中的json常見用法實(shí)例詳解
博主在開發(fā)一些C端小軟件時(shí),喜歡用json作為序列化方案,故總結(jié)下python中json庫常見用法。
導(dǎo)包
自帶的庫,無需額外安裝。
import json
api介紹
序列化:
這里可以理解為將python中的各種數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)化為json字符串的過程。
涉及api:dump、dumps
反序列化:
將輸入的json字符串,轉(zhuǎn)化為python對象的過程。
涉及api:load、loads
加s和不加s的區(qū)別:
以反序列化為例,如果需要從文件中讀取數(shù)據(jù),則使用load,直接傳入文件描述符。

簡而言之,就是需要從文件中讀寫數(shù)據(jù)時(shí),使用load、dump,否則使用loads、dumps
常見用法
json轉(zhuǎn)python內(nèi)置對象
json會(huì)被適當(dāng)?shù)剞D(zhuǎn)化為python中的list或者dic類型的對象。
字典對象
代碼示例:
user_dic = json.loads('{"name": "admin", "age": 20, "children": {"name": "child1", "age": 1}}')
print(type(user_dic))
print(user_dic)運(yùn)行結(jié)果:
<class 'dict'>
{'name': 'admin', 'age': 20, 'children': {'name': 'child1', 'age': 1}}
數(shù)組對象
代碼示例:
user_list = json.loads('[1,2,3,4]')
print(type(user_list))
print(user_list)運(yùn)行結(jié)果:
<class 'list'>
[1, 2, 3, 4]
文件讀取
代碼示例:
with open('out.json', mode='r', encoding='utf-8') as fp:
user_dic = json.load(fp=fp)
print(type(user_dic))
print(user_dic)文件中存儲(chǔ)的json
{
"age": 20,
"children": {
"age": 1,
"name": "child1"
},
"name": "admin"
}運(yùn)行結(jié)果:
<class 'dict'>
{'age': 20, 'children': {'age': 1, 'name': 'child1'}, 'name': 'admin'}
python內(nèi)置對象轉(zhuǎn)json
字典轉(zhuǎn)json
json_str = json.dumps({'name': 'admin', 'age': 20, 'children': {'name': 'child1', 'age': 1}})
print(type(json_str))
print(json_str)結(jié)果:
<class 'str'>
{"name": "admin", "age": 20, "children": {"name": "child1", "age": 1}}
字典轉(zhuǎn)json(壓縮存儲(chǔ))
如果存儲(chǔ)后的數(shù)據(jù)并不用于人工閱讀,可以考慮去除所有地空格和換行。
json_str = json.dumps({'name': 'admin', 'age': 20, 'children': {'name': 'child1', 'age': 1}}, separators=(',', ':'))
print(type(json_str))
print(json_str)結(jié)果:
<class 'str'>
{"name":"admin","age":20,"children":{"name":"child1","age":1}}
字典轉(zhuǎn)json(美化輸出)
適用于對外展示,提高可讀性;這里的indent=4表示縮進(jìn)空格數(shù)。
json_str = json.dumps({'name': 'admin', 'age': 20, 'children': {'name': 'child1', 'age': 1}}, sort_keys=True, indent=4)
print(type(json_str))
print(json_str)結(jié)果:
<class 'str'>
{
"age": 20,
"children": {
"age": 1,
"name": "child1"
},
"name": "admin"
}
文件讀取
with open('out.json', mode='w+', encoding='utf-8') as fp:
json.dump(fp=fp, obj={'name': 'admin', 'age': 20, 'children': {'name': 'child1', 'age': 1}}, sort_keys=True, indent=4)自定義對象
如果是自定義的對象,需要先將對象轉(zhuǎn)化為字典類型,再使用json庫相關(guān)的api。
普通對象
class Child:
def __init__(self, name):
self.name = name
class Student:
def __init__(self, name, age):
self.name = name
self.age = age單個(gè)對象
# 序列化對象
s_str = json.dumps(Student('admin', 18).__dict__)
print(s_str)
# 反序列化對象
student_obj = Student(**json.loads(s_str))
print(student_obj)數(shù)組對象
# 序列化數(shù)組
s_list = [Student('admin1', 1), Student('admin2', 2)]
s_str = json.dumps([obj.__dict__ for obj in s_list])
print(s_str)
# 反序列化數(shù)組
student_list = []
for st in json.loads(s_str):
student_list.append(Student(**st))
print(student_list)嵌套對象
出現(xiàn)嵌套對象時(shí),思路也是一樣的,都優(yōu)先轉(zhuǎn)化為字典。
class Child:
def __init__(self, name):
self.name = name
def __str__(self):
return "{0}".format(self.name)
class Student:
def __init__(self, name, age, children: Child):
self.name = name
self.age = age
self.children = children
def __str__(self):
return "{0}, {1}, children:{2}".format(self.name, self.age, self.children)單個(gè)對象
# 序列化
s_str = json.dumps(Student('admin', 18, Child('son')), default=lambda o: o.__dict__, indent=4)
print(s_str)
# 反序列化
decode_s = Student(**json.loads(s_str))
print(decode_s)對象數(shù)組
# 序列化
s_list = [Student('admin1', 1, Child('son1')), Student('admin2', 2, Child('son2'))]
s_str = json.dumps([obj.__dict__ for obj in s_list], default=lambda o: o.__dict__, indent=4)
print(s_str)
# 反序列化最外層套了一個(gè)list,其他與單個(gè)對象一致。補(bǔ)充知識點(diǎn)
上述示例中出現(xiàn)的 ** 是一種傳參方式,接收字典類型的數(shù)據(jù)。
def func(**kwargs):
print(kwargs['a'])
print(kwargs['b'])
print(type(kwargs))
s_dic = {'a': 1, "b": 2}
func(**s_dic)輸出結(jié)果為
1
2
<class 'dict'>
到此這篇關(guān)于Python 中的json常見用法的文章就介紹到這了,更多相關(guān)python json用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
分析語音數(shù)據(jù)增強(qiáng)及python實(shí)現(xiàn)
數(shù)據(jù)增強(qiáng)是一種生成合成數(shù)據(jù)的方法,即通過調(diào)整原始樣本來創(chuàng)建新樣本。這樣我們就可獲得大量的數(shù)據(jù)。這不僅增加了數(shù)據(jù)集的大小,還提供了單個(gè)樣本的多個(gè)變體,這有助于我們的機(jī)器學(xué)習(xí)模型避免過度擬合2021-06-06
Win10用vscode打開anaconda環(huán)境中的python出錯(cuò)問題的解決
這篇文章主要介紹了Win10用vscode打開anaconda環(huán)境中的python出錯(cuò),本文給大家分享解決方案,給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05
python實(shí)現(xiàn)自動(dòng)網(wǎng)頁截圖并裁剪圖片
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)自動(dòng)網(wǎng)頁截圖并裁剪圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
一文教你學(xué)會(huì)使用Python中的多處理模塊
Python?多處理模塊是一個(gè)強(qiáng)大的工具,用于實(shí)現(xiàn)并行處理,提高程序的性能和效率,本文將詳細(xì)介紹?Python?中多處理模塊的使用方法,希望對大家有所幫助2024-01-01
Python爬蟲庫BeautifulSoup獲取對象(標(biāo)簽)名,屬性,內(nèi)容,注釋
如何利用Python爬蟲庫BeautifulSoup獲取對象(標(biāo)簽)名,屬性,內(nèi)容,注釋等操作下面就為大家介紹一下2020-01-01
python安裝/卸載模塊方法步驟詳解(附詳細(xì)圖解)
在日常工作中會(huì)需要安裝或者卸載Python模塊.于是我整理了一下,下面這篇文章主要給大家介紹了關(guān)于python安裝/卸載模塊的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01
python多進(jìn)程(加入進(jìn)程池)操作常見案例
這篇文章主要介紹了python多進(jìn)程(加入進(jìn)程池)操作,結(jié)合常見案例形式分析了Python多進(jìn)程復(fù)制文件、加入進(jìn)程池及多進(jìn)程聊天等相關(guān)操作技巧,需要的朋友可以參考下2019-10-10
python之yield表達(dá)式學(xué)習(xí)
這篇文章主要介紹了python之yield表達(dá)式學(xué)習(xí),python中有一個(gè)略微奇怪的表達(dá)式叫yield expression,本文就來探究一下這是個(gè)什么東西,需要的朋友可以參考下2014-09-09
python批量修改圖片尺寸,并保存指定路徑的實(shí)現(xiàn)方法
今天小編就為大家分享一篇python批量修改圖片尺寸,并保存指定路徑的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07

