json 支持数据格式
1.对象(字典) 花括号
2.数组(列表) 中括号
3.整形、浮点型、布尔类型 null 类型
4.字符串类型 (字符串必须要用双引号,不能用单引号)
多个数据之间使用逗号
注意:json本质就是一个字符串
json dump/dumps 方法
作用转换为json
json.dump 存与文件中
json.dumps 转换为json字符串
注意点:中文转换问题,dump 的时候只能存放ascii字符
def dump_test(): # 中文存储在json文件中,open 文件指定编码,utf-8, json.dump 关闭ensure_ascii json_str = json.dumps(persons) print(json_str) with open('person.json','w',encoding='utf-8') as fp: # fp.write(json_str) json.dump(persons,fp,ensure_ascii=False)
json load/loads 方法
json 转换为python 字典def load_test(): json_str = '[{"username": "张三", "age": 18, "country": "china"}, {"username": "李赛", "age": 20, "country": "china"}]' persons = json.loads(json_str) print(type(persons)) for person in persons: print(person) with open('person.json', 'r', encoding='utf-8') as fp: persons = json.load(fp) print(type(persons)) for person in persons: print(person) ------------- 输出结果 <class 'list'> {'username': '张三', 'age': 18, 'country': 'china'} {'username': '李赛', 'age': 20, 'country': 'china'} <class 'list'> {'username': '张三', 'age': 18, 'country': 'china'} {'username': '李四', 'age': 20, 'country': 'china'}