Python中Json使用示例詳解
Python Json使用
本篇主要介紹一下 python 中 json的使用 如何把 dict轉(zhuǎn)成json 、object 轉(zhuǎn)成json 、以及json轉(zhuǎn)成對象 等等。。
json是非常常用的一種數(shù)據(jù)格式,比如在前后端分離的 web開發(fā)中,返回給前端 通常都會使用json ,那么來看看 python 中如何玩轉(zhuǎn)json
1.dict 轉(zhuǎn)成 json (json.dumps(dict))
注意: ensure_ascii=False 否則中文亂碼
import json
student = {
'name': 'johnny',
'age': 27,
'address': '無錫'
}
print(json.dumps(student, ensure_ascii=False))
# {"name": "johnny", "age": 27, "address": "無錫"} json2.json 轉(zhuǎn) dict (json.loads(jsonstr))
import json
json_student = '{"name": "johnny", "age": 27, "address": "無錫"}'
print(json.loads(json_student))
# {'name': 'johnny', 'age': 27, 'address': '無錫'} 字典dict3. 類對象轉(zhuǎn) json (dict屬性/提供default=方法)
3.1 錯誤使用
注意:json.dumps() 不支持 直接把 類對象放進去?。?! 會報錯 Student is not JSON serializable
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student('candy', '30')
#錯誤使用?。?!
print(json.dumps(student)) 報錯?。?! TypeError: Object of type Student is not JSON serializable3.2 使用類對象 dict 屬性
#正確使用!??!
print(json.dumps(student.__dict__))) #可以使用 類對象的 __dict__ 屬性
#{"name": "candy", "age": "30"}3.3 提供一個 convert2json 方法
default=指定方法
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def conver2json(self):
return {
'name': self.name,
'age': self.age
}
#通過自己寫一個 conver2json方法 去手動轉(zhuǎn)化一下 把 類對象轉(zhuǎn)成json
print(json.dumps(student,default=Student.conver2json))4.json 轉(zhuǎn) 類對象 (json.loads(jsonstr,object_hook=..))
注意:json.loads 默認只會轉(zhuǎn)成dict,需要自己提供方法 把dict 轉(zhuǎn)成 類對象
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def conver2json(self):
return {
'name': self.name,
'age': self.age
}
@staticmethod
def convert2object(dict):
return Student(dict['name'],dict['age'])
json_student = '{"name": "johnny", "age": 27, "address": "無錫"}'
print(json.loads(json_student,object_hook=Student.convert2object))
#<__main__.Student5. dict/對象 轉(zhuǎn)為 json文件 (json.dump(student,f))
注意 dump 還是 只能接收 dict ,如果要把 對象寫到j(luò)son中 需要先把對象 轉(zhuǎn)成 dict ,可以通過 ——dict——屬性
student = {
'name': 'johnny',
'age': 27,
'address': '無錫'
}
with open('student.json','w') as f:
json.dump(student,f,ensure_ascii=False)6. json文件轉(zhuǎn) dict /對象 (json.load)
with open('student.json','r') as f:
print(json.load(f))小疑問
為什么:轉(zhuǎn)成json 后 name 是一個數(shù)組呢? 因為 self.name = name, 后面有一個 逗號,。。。 會把這個name當(dāng)成元組 ,元組轉(zhuǎn)成 json 就是 數(shù)組?。?!
class Student:
def __init__(self, name, age):
self.name = name, #這里?。?!不能有 逗號。。
self.age = age
student = Student('candy', '30')
print(json.dumps(student.__dict__))
#猜猜它的打印是什么
#{"name": ["candy"], "age": "30"} 總結(jié)
- json.dumps() 只支持 dict轉(zhuǎn)json 如果是 class 對象 需要 通過 dict屬性或者提供default= conver2json 方法
- json.dump() 是寫入 文件中
- json.loads() 只支持把 json str轉(zhuǎn)成 dict ,如果要轉(zhuǎn)成 class 對象 則需要提供 object_hook=convert2object方法
- json.load()/ 是從文件中讀取 jsonstr 到 dict
很簡單 注意一下 class 和 json 的相互轉(zhuǎn)化即可
參考:http://www.dhdzp.com/article/256548.htm
到此這篇關(guān)于Python中Json使用詳解的文章就介紹到這了,更多相關(guān)Python Json使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于python list對象中嵌套元組使用sort時的排序方法
下面小編就為大家分享一篇基于python list對象中嵌套元組使用sort時的排序方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python機器學(xué)習(xí)NLP自然語言處理基本操作關(guān)鍵詞
本文是Python機器學(xué)習(xí)NLP自然語言處理系列文章,帶大家開啟一段學(xué)習(xí)自然語言處理 (NLP) 的旅程. 本文主要學(xué)習(xí)NLP自然語言處理關(guān)鍵詞的操作2021-09-09
從零學(xué)Python之入門(二)基本數(shù)據(jù)類型
這是繼“hello world”之后的第二篇入門級基礎(chǔ)知識,以后這個系列會按照入門、進階、精通三個分類進行下去,歡迎高手們來拍磚2014-05-05
Python基礎(chǔ)學(xué)習(xí)函數(shù)+模塊+類
這篇文章主要介紹了Python基礎(chǔ)學(xué)習(xí)函數(shù)+模塊+類,這是基礎(chǔ)學(xué)習(xí)的第三篇內(nèi)容,小編已把前兩篇鏈接放在下面,需要學(xué)習(xí)的同學(xué)可以參考一下2022-05-05
利用Python實現(xiàn)去重聚合Excel數(shù)據(jù)并對比兩份數(shù)據(jù)的差異
在數(shù)據(jù)處理過程中,常常需要將多個數(shù)據(jù)表進行合并,并進行比對,以便找出數(shù)據(jù)的差異和共同之處,本文將介紹如何使用 Pandas 庫對兩個 Excel 數(shù)據(jù)表進行合并與比對,需要的可以參考下2023-11-11
Python使用Dijkstra算法實現(xiàn)求解圖中最短路徑距離問題詳解
這篇文章主要介紹了Python使用Dijkstra算法實現(xiàn)求解圖中最短路徑距離問題,簡單描述了Dijkstra算法的原理并結(jié)合具體實例形式分析了Python使用Dijkstra算法實現(xiàn)求解圖中最短路徑距離的相關(guān)步驟與操作技巧,需要的朋友可以參考下2018-05-05

