#json javaScript Object Notation
#对象 {key1:value1,key2:value2} key为对象属性,value为对应的值;
#数组 []数组是比较特殊的数据类型,可以像对象那样使用键值对,但还是索引用的多;
json 数据需要用双引号包围。
import json
str = """
[{
"name":"Bob",
"gender":"male",
"birthday":"1992-10-18"
},{"name":"Selina",
"gender":"female",
"birthday":"1995-10-18"
}]
"""
#读取json loads()
print(type(str))
date = json.loads(str)
print(date)
print(type(date))
# print(date[0])
# print(date[0].get('name'))
# print(date[0].get('age'))
#写入
with open ('date.json','w') as f:
# 利用dumps()将json对象转为字符串,然后调用write()方法写入
# f.write(json.dumps(date))
# indent缩进字符串个数
f.write(json.dumps(date,indent=2))
#指定编码
with open('date.json','w',encoding='utf-8') as f:
f.write(json.dumps(date,indent=2,ensure_ascii=False))
#读取
with open('date.json','r') as f:
str1 = f.read()
date = json.loads(str1)
print(date)