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'}