一、什麼是JSON
JSON是一種輕量級的數據交換格式,具有良好的可讀性和可擴展性。它由JavaScript對象表示語法擴展而來,是一種文本格式,易於人們閱讀和編寫,同時也易於機器解析和生成。
JSON採用鍵值對的方式來描述數據,其中鍵值對之間用逗號進行分隔,同時採用大括號將鍵值對包含起來,形成一個JSON對象。例如:
{ "name": "Tom", "age": 25, "gender": "male" }
二、Python轉JSON方法
1.使用json.dumps()
Python內置了json模塊,其中的dumps()方法可以將Python對象轉換為JSON格式。dumps()方法具有多個參數,其中indent參數可以用於指定縮進空格數,ensure_ascii參數可以用於指定是否將非ascii字符轉義成\uXXXX形式。
示例代碼:
import json data = { "name": "Tom", "age": 25, "gender": "male" } json_data = json.dumps(data, indent=4, ensure_ascii=False) print(json_data)
輸出結果:
{ "name": "Tom", "age": 25, "gender": "male" }
2.使用json.dump()
與dumps()相似,dump()方法可以將Python對象轉換為JSON格式,並將結果寫入到文件中。
示例代碼:
import json data = { "name": "Tom", "age": 25, "gender": "male" } with open('data.json', 'w') as fp: json.dump(data, fp, indent=4, ensure_ascii=False)
3.使用json.JSONEncoder()
JSONEncoder類是Python中json模塊的一個非常重要的類,它可以將Python對象轉換為JSON格式,可以重載默認的轉換邏輯,支持自定義類的序列化方式。
示例代碼:
import json class Person: def __init__(self, name, age): self.name = name self.age = age class PersonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Person): return {"name": obj.name, "age": obj.age} return json.JSONEncoder.default(self, obj) person = Person("Tom", 25) json_data = json.dumps(person, cls=PersonEncoder, indent=4, ensure_ascii=False) print(json_data)
輸出結果:
{ "name": "Tom", "age": 25 }
三、JSON轉Python方法
1.使用json.loads()
loads()方法可以將JSON格式的字符串轉換為Python對象。
示例代碼:
import json json_data = '{"name": "Tom", "age": 25, "gender": "male"}' data = json.loads(json_data) print(data)
輸出結果:
{'name': 'Tom', 'age': 25, 'gender': 'male'}
2.使用json.load()
load()方法可以將JSON格式的數據從文件中讀取,並轉換為Python對象。
示例代碼:
import json with open('data.json', 'r') as fp: data = json.load(fp) print(data)
四、總結
以上就是Python中JSON的轉換方法,通過將Python對象轉換成易於傳輸和解析的JSON格式,我們可以更加方便地在不同的系統之間進行數據交換,同時也可以對數據進行格式化和驗證。
原創文章,作者:ESOMI,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/372154.html