欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中Json使用示例詳解

 更新時(shí)間:2022年07月23日 14:52:45   作者:AskaJohnny  
這篇文章主要介紹了Python中Json使用,主要介紹一下python?中?json的使用?如何把dict轉(zhuǎn)成json?、object?轉(zhuǎn)成json?、以及json轉(zhuǎn)成對象,需要的朋友可以參考下

Python Json使用

本篇主要介紹一下 python 中 json的使用 如何把 dict轉(zhuǎn)成json 、object 轉(zhuǎn)成json 、以及json轉(zhuǎn)成對象 等等。。

json是非常常用的一種數(shù)據(jù)格式,比如在前后端分離的 web開發(fā)中,返回給前端 通常都會(huì)使用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": "無錫"}  json

2.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': '無錫'} 字典dict

3. 類對象轉(zhuǎn) json (dict屬性/提供default=方法)

3.1 錯(cuò)誤使用

注意:json.dumps() 不支持 直接把 類對象放進(jìn)去!??! 會(huì)報(bào)錯(cuò) Student is not JSON serializable

import json
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
student = Student('candy', '30')
#錯(cuò)誤使用!?。?
print(json.dumps(student))  報(bào)錯(cuò)?。。?TypeError: Object of type Student is not JSON serializable

3.2 使用類對象 dict 屬性

#正確使用?。?!
print(json.dumps(student.__dict__))) #可以使用 類對象的 __dict__ 屬性
#{"name": "candy", "age": "30"}

3.3 提供一個(gè) 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
        }
#通過自己寫一個(gè) conver2json方法 去手動(dòng)轉(zhuǎn)化一下 把 類對象轉(zhuǎn)成json 
print(json.dumps(student,default=Student.conver2json))

4.json 轉(zhuǎn) 類對象 (json.loads(jsonstr,object_hook=..))

注意:json.loads 默認(rèn)只會(huì)轉(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__.Student

5. 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 是一個(gè)數(shù)組呢? 因?yàn)?self.name = name, 后面有一個(gè) 逗號,。。。 會(huì)把這個(gè)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.dbjr.com.cn/article/256548.htm

到此這篇關(guān)于Python中Json使用詳解的文章就介紹到這了,更多相關(guān)Python Json使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python實(shí)現(xiàn)的多任務(wù)版udp聊天器功能案例

    python實(shí)現(xiàn)的多任務(wù)版udp聊天器功能案例

    這篇文章主要介紹了python實(shí)現(xiàn)的多任務(wù)版udp聊天器功能,結(jié)合具體案例形式分析了Python基于udp的聊天器功能相關(guān)實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下
    2019-11-11
  • Selenium的使用詳解

    Selenium的使用詳解

    今天小編就為大家分享一篇關(guān)于Selenium的使用詳解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • Python使用ctypes調(diào)用C/C++的方法

    Python使用ctypes調(diào)用C/C++的方法

    今天小編就為大家分享一篇關(guān)于Python使用ctypes調(diào)用C/C++的方法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • pandas數(shù)據(jù)集的端到端處理

    pandas數(shù)據(jù)集的端到端處理

    今天小編就為大家分享一篇關(guān)于pandas數(shù)據(jù)集的端到端處理,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • Python與R語言的簡要對比

    Python與R語言的簡要對比

    這篇文章主要介紹了Python與R語言的簡要對比,小編覺得還挺不錯(cuò)的,這里分享給大家,需要的朋友可以了解下。
    2017-11-11
  • 淺談matplotlib中FigureCanvasXAgg的用法

    淺談matplotlib中FigureCanvasXAgg的用法

    這篇文章主要介紹了淺談matplotlib中FigureCanvasXAgg的用法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • 對python 中re.sub,replace(),strip()的區(qū)別詳解

    對python 中re.sub,replace(),strip()的區(qū)別詳解

    今天小編就為大家分享一篇對python 中re.sub,replace(),strip()的區(qū)別詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python基礎(chǔ)之集合

    python基礎(chǔ)之集合

    這篇文章主要介紹了python集合,實(shí)例分析了Python中返回一個(gè)返回值與多個(gè)返回值的方法,需要的朋友可以參考下
    2021-10-10
  • Golang與python線程詳解及簡單實(shí)例

    Golang與python線程詳解及簡單實(shí)例

    這篇文章主要介紹了Golang與python線程詳解及簡單實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • pytorch1.0中torch.nn.Conv2d用法詳解

    pytorch1.0中torch.nn.Conv2d用法詳解

    今天小編就為大家分享一篇pytorch1.0中torch.nn.Conv2d用法詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01

最新評論