JSON文件存储 了解如何利用python保存数据到JSON文件
import json
'''
在javascript 语言中,一切都是对象,
对象和数组是比较特殊而且常用的类型
对象:{key1:value1,key2:value2}
数组结构为["java","javascript"]
'''
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))
print(data[0]['name'])
print(data[0].get('name'))
print(data[0].get('age'))
print(data[0].get('age'),25)
print('我们可以调用dumps方法将json对象转化为字符串')
data =[{
'name':'Bob',
'gender':'male',
'birthday':'1992-02-03'
}]
with open('data.json','w') as file:
file.write(json.dumps(data,indent=2))
data =[{
'name':'王伟',
'gender':'male',
'birthday':'1992-02-03'
}]
with open('data.json','w',encoding='utf-8') as file:
file.write(json.dumps(data,indent=2,ensure_ascii=False))
|