三、写入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识别