文件操作基础之写入JSON文件

三、写入JSON文件

JSON全称为JavaScript Object Notation

JSON官方网站:http://json.org/

1.JSON与Python

JSON Python
object dict
array list
string str
number (int / real) int / flfloat
true / false True / False
null None

2.Python与JSON

Python JSON
dict object
list, tuple array
str string
int, flfloat, int- & flfloat-derived Enums number
True / False true / false
None null

例子:

import json
def main():
    mydict={
    "name": "小明",
    "age": 18,
    "qq": 10000,
    "friends": ["小红", "小兰"],
    "cars": [
    {"brand": "BYD", "max_speed": 180},
    {"brand": "Audi", "max_speed": 280},
    {"brand": "Benz", "max_speed": 320}
   ]
  }
    try:
        with open('data.json', 'w', encoding='utf-8') as fs:
            json.dump(mydict, fs)
    except IOError as e:
            print(e)
    print('保存数据成功!')


if __name__ == '__main__':
            main()

在这里插入图片描述

在data.json中可以看到里面的内容

{"name": "\u5c0f\u660e", "age": 18, "qq": 10000, "friends": ["\u5c0f\u7ea2", "\u5c0f\u5170"], "cars": [{"brand": "BYD", "max_speed": 180}, {"brand": "Audi", "max_speed": 280}, {"brand": "Benz", "max_speed": 320}]}

3.json模块有四个重要的函数

  • dump -将Python对象按照JSON格式序列化到文件中
  • dumps -将Python对象处理成JSON格式的字符串
  • load -将文件中的JSON数据反序列化成对象
  • loads -将字符串的内容反序列化成Python对象

序列化:指将数据结构或对象状态转换为可以存储或传输的形式,这样在需要的时候能够恢复到原先的状态,而且通过序列化的数据重新获取字节时,可以利用这些字节来产生原始对象的副本(拷贝) 。相反的操作则为反序列化。

4.requests模块

先下载

pip install requests

在这里插入图片描述

例子:

import requests
import json


def main():

 resp = requests.get('https://github.com/Ranxf')
 print(resp.status_code)

 print('============================================')
 
 resp1 = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'})
 print(resp1.url)
 print(resp1.text)


if __name__ == '__main__':
    main()

运行结果

D:\python3.7.4\untitled\venv\Scripts\python.exe D:/python3.7.4/untitled/test0228.py
200
============================================
https://dict.baidu.com/s?wd=python
....
....
....
....
....
require.config(
    {
        baseUrl: '/static/asset/asset',
        urlArgs: 'v=201703281500',
        'packages': [
            {
                'name': 'etpl',
                'location': '../dep/etpl',
                'main': 'main'
            }
        ]
    }
);
require(['main', 'sug_pc'], function(mian, sug_pc){
    sug_pc.init();
});

$("#kw")[0].focus();
window.__finish_time = + (new Date());
window.__used_time = __finish_time - window.__start_time;
</script>
</div>
</body>
</html>



Process finished with exit code 0

除了json模外,还有pickle和shelve两个模块也能实现序列化,但只能被Python识别

发布了134 篇原创文章 · 获赞 16 · 访问量 6333

猜你喜欢

转载自blog.csdn.net/weixin_46108954/article/details/104649507
今日推荐