Python基础 | Json模块简单应用

2022/1/28 20:05:26

本文主要是介绍Python基础 | Json模块简单应用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

# -*- UTF-8 -*-
"""
@File:Json文本文件存储.py
@Description:Json模块简单使用
@Author:echohye
@Date:2022/01/28
"""

import json

data = [{
    'name': 'Bob',
    'gender': 'male',
    'birthday': '2022-2-30'
}, {
    'name': 'Mary',
    'gender': 'female',
    'birthday': '2022-2-28'
}]

'''
@Author:echohye
@Description:json.dumps()
@Date:2022-01-28, 周五, 19:03
'''
def dumpsToJson():
    with open('dumps.json', 'w', encoding='utf-8') as f:
        f.write(json.dumps(data))


'''
@Author:echohye
@Description:josn.dump()
@Date:2022-01-28, 周五, 19:03
'''
def dumpToJson():
    json.dump(data, open('dump.json', 'w'), indent=2)

'''
@Author:echohye
@Description:json.loads()
@Date:2022-01-28, 周五, 19:12
'''
def loadsToStr():
    with open('dumps.json','r',encoding='utf-8') as f:
        loads = json.loads(f.read())
        print(loads)

'''
@Author:echohye
@Description:json.load()
@Date:2022-01-28, 周五, 19:16
'''
def loadTostr():
    load = json.load(open('dump.json', 'r', encoding='utf-8'))
    print(load)

if __name__ == '__main__':
    dumpsToJson()
    dumpToJson()
    loadsToStr()
    loadTostr()


这篇关于Python基础 | Json模块简单应用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程