Python Json使用

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"}   

總結

  1. json.dumps() 只支持 dict轉json 如果是 class 對象 需要 通過 dict屬性或者提供default= conver2json 方法
  2. json.dump() 是寫入 文件中
  3. json.loads() 只支持把 json str轉成 dict ,如果要轉成 class 對象 則需要提供 object_hook=convert2object方法
  4. json.load()/ 是從文件中讀取 jsonstr 到 dict

很簡單 注意一下 class 和 json 的相互轉化即可

參考:http://www.kaotop.com/it/26500.html

歡迎大家訪問 個人博客 Johnny小屋
歡迎關注個人公衆號

歡迎關注個人公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章