爬虫17-json用法
1.dump
import json persons=[ { 'username':"wangchenyang", 'age':14, 'country':"china" }, { 'username':"王晨阳", 'age':14, 'country':"china" } ] # json_str=json.dumps(persons) # print(json_str) with open('person.json','w',encoding="utf-8") as fp: json.dump(persons,fp,ensure_ascii=False)
2.load
import json # json_str='[{"username": "wangchenyang", "age": 14, "country": "china"}, {"username": "王晨阳", "age": 14, "country": "china"}]' # persons=json.loads(json_str) # for person in persons: # print(person) with open('person.json','r',encoding="utf-8") as fp: persons = json.load(fp) for person in persons: print(person)