self_example/Spider/Chapter04_数据存储/saveJson.py

51 lines
962 B
Python

# -*- encoding:utf-8 -*-
'''
@Author : dingjiawen
@Date : 2023/12/6 14:39
@Usage :
@Desc : 保存成Json
'''
import json
str = '''
[{
"name": "Bob",
"gender": "male",
"birthday": "1992-10-18"
}, {
"name": "Selina",
"gender": "female",
"birthday": "1995-10-18"
}]
'''
print(type(str))
data = json.loads(str)
print(data)
print(type(data))
import json
data = [{
'name': 'Bob',
'gender': 'male',
'birthday': '1992-10-18'
}]
with open('data.json', 'w', encoding='utf-8') as file:
file.write(json.dumps(data))
with open('data.json', 'w', encoding='utf-8') as file:
# indent就是有缩进的
file.write(json.dumps(data, indent=2))
data = [{
'name': '张三',
'gender': 'male',
'birthday': '1992-10-18'
}]
with open('data.json', 'w', encoding='utf-8') as file:
# indent就是有缩进的,ensure_ascii规定编码格式(输出中文)
file.write(json.dumps(data, indent=2, ensure_ascii=False))