Python Json使用
本篇主要介紹一下 python 中 json的使用 如何把 dict轉成json 、object 轉成json 、以及json轉成物件 等等,,
json是非常常用的一種資料格式,比如在前后端分離的 web開發中,回傳給前端 通常都會使用json ,那么來看看 python 中如何玩轉json
1.dict 轉成 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": "無錫"} json
2.json 轉 dict (json.loads(jsonstr))
import json
json_student = '{"name": "johnny", "age": 27, "address": "無錫"}'
print(json.loads(json_student))
# {'name': 'johnny', 'age': 27, 'address': '無錫'} 字典dict
3. 類物件轉 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 serializable
3.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方法 去手動轉化一下 把 類物件轉成json
print(json.dumps(student,default=Student.conver2json))
4.json 轉 類物件 (json.loads(jsonstr,object_hook=..))
注意:json.loads 默認只會轉成dict,需要自己提供方法 把dict 轉成 類物件
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__.Student
5. dict/物件 轉為 json檔案 (json.dump(student,f))
注意 dump 還是 只能接收 dict ,如果要把 物件寫到json中 需要先把物件 轉成 dict ,可以通過 ——dict——屬性
student = {
'name': 'johnny',
'age': 27,
'address': '無錫'
}
with open('student.json','w') as f:
json.dump(student,f,ensure_ascii=False)
6. json檔案轉 dict /物件 (json.load)
with open('student.json','r') as f:
print(json.load(f))
小疑問
為什么:轉成json 后 name 是一個陣列呢? 因為 self.name = name, 后面有一個 逗號,,,, 會把這個name當成元組 ,元組轉成 json 就是 陣列!!!
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"}
總結
- json.dumps() 只支持 dict轉json 如果是 class 物件 需要 通過 dict屬性或者提供default= conver2json 方法
- json.dump() 是寫入 檔案中
- json.loads() 只支持把 json str轉成 dict ,如果要轉成 class 物件 則需要提供 object_hook=convert2object方法
- json.load()/ 是從檔案中讀取 jsonstr 到 dict
很簡單 注意一下 class 和 json 的相互轉化即可
參考:http://www.kaotop.com/it/26500.html
歡迎大家訪問 個人博客 Johnny小屋
歡迎關注個人公眾號

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500097.html
標籤:其他
下一篇:Python做一個英漢翻譯小字典
