标签:class pytho div import pen 字符 对象 asc obj
用解析器解析出的数据后,可以通过TXT、JSON、CSV等文件形式进行存储;
1、TXT形式此处略;
2、JSON文件存储
json即js 对象标记,是一种数据格式;
json格式:
json对象:{"username":"ADMIN","pwd":"xxxx","address":"北京"}
json数组:[{"name":"smith","age":"23"},{"name":"jones","age":"23"},{"name":"zye","age":"23"}]
例如:
1 import json 2 str=‘‘‘ 3 [{"name":"小明","age":"23"},{"name":"jones","age":"23"},{"name":"zye","age":"23"}] 4 ‘‘‘ 5 print(type(str)) 6 obj=json.loads(str)#将json格式字符串转为json 7 print(type(obj)) 8 #取值 9 print(obj[0][‘name‘]) 10 print(obj[1][‘age‘]) 11 print(obj[1].get(‘name‘)) 12 print(obj[1].get(‘address‘,‘北京‘))#即如果该字段为None或者该key不存在时,会采用默认值;即第二个参数为默认值 13 14 #加载一个json文件 15 with open("read.json",‘r‘) as file: 16 s=file.read() 17 j=json.loads(s) 18 print(j[0][‘name‘]) 19 20 #输出json 21 jsonArray=[{‘name‘:‘sd‘},{‘name‘:‘ss‘}] 22 with open(‘test.json‘,‘w‘) as file: 23 file.write(json.dumps(jsonArray)) 24 25 #或者: 26 jsonObj=json.loads(str) 27 with open(‘test.json‘,‘w‘) as file: 28 file.write(json.dumps(jsonObj)) 29 30 #或者:如果有中文,且想格式化 31 jsonObj=json.loads(str) 32 with open(‘test.json‘,‘w‘,encoding=‘utf-8‘) as file: 33 file.write(json.dumps(jsonObj,indent=2,ensure_ascii=False))#格式化了json,
写入test.json后格式:
[
{
"name": "小明",
"age": "23"
},
{
"name": "jones",
"age": "23"
},
{
"name": "zye",
"age": "23"
}
]
标签:class pytho div import pen 字符 对象 asc obj
原文地址:https://www.cnblogs.com/ygzhaof/p/10209805.html