Python處理json檔案
阿新 • • 發佈:2022-05-13
Python處理json檔案
JSON資料處理型別:
序列化: 將python中的資料型別轉換為JSON格式字串
反序列化:將JSON格式字串轉換為python中的資料型別
json庫提供四種方法:json.dumps()
、json.dump()
、json.loads()
、json.load()
1. json.dump()
將python資料型別寫入json檔案(案例是將字典寫入json檔案)
import json filename = "student.json" student = {"name":"CC", "age":20, "height":1.75} with open (filename, 'w') as f: json.dump(student, f)
2. json.dumps()
將python資料型別轉換成json字串(案例是將字典轉換為字串)
import json
student = {"name":"CC", "age":20, "height":1.75}
student_json = json.dumps (student)
print (type(student_json))
print (student_json)
3. json.load()
將json檔案讀入,存放到python資料型別(案例是讀取json檔案,返回物件型別是字典)
import json filename = "student.json" with open (filename , 'r') as f: students = json.load (f) print (type (students)) print (students)
4. json.loads()
將字串轉換為python資料型別(案例是將字串轉換為字典)
import json
student_str = "{\"name\":\"CC\", \"age\":20, \"height\":1.75}"
student_dict = json.loads (student_str)
print (type(student_dict))
print (student_dict)