一、什麼是Json
JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,易於閱讀和編寫,同時也易於機器解析和生成。它基於JavaScript語法,但與之無關。JSON具有良好的可讀性和擴展性,已經成為廣泛應用的數據交換格式,被廣泛用於Web服務之間的數據通信。
二、Json轉Python對象
Python內置的json模塊提供了將json字元串轉化為python對象的功能。其中主要有以下幾個函數:
- json.loads():將json字元串解碼為Python對象。
- json.load():從文件讀取json,並將其解碼為Python對象。
import json
#json字元串
json_str = '{"name":"Tom", "age": 18, "gender": "male"}'
#將json字元串轉化為Python對象
python_obj = json.loads(json_str)
print(python_obj)
#輸出結果:{'name': 'Tom', 'age': 18, 'gender': 'male'}
三、Python對象轉Json
同樣,Python內置的json模塊也提供了將python對象轉化為json字元串的功能。其中主要有以下幾個函數:
- json.dumps():將Python對象編碼成json字元串。
- json.dump():將Python對象編碼成json字元串,並寫入文件。
import json
#Python對象
python_obj = {
"name": "Tom",
"age": 18,
"gender": "male"
}
#將Python對象轉化為json字元串
json_str = json.dumps(python_obj)
print(json_str)
#輸出結果:{"name": "Tom", "age": 18, "gender": "male"}
四、Json轉Python自定義對象
json模塊只能將json字元串轉化為Python內置類型的對象,但是我們也可以通過一些自定義的方式,將json字元串轉化為Python自定義類型的對象。
import json
#自定義類
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
#json字元串
json_str = '{"name":"Tom", "age": 18, "gender": "male"}'
#將json字元串轉化為Python內置類型的對象
python_obj = json.loads(json_str)
#將Python內置類型對象轉化為自定義類型的對象
person = Person(**python_obj)
print(person.name, person.age, person.gender)
#輸出結果:Tom 18 male
五、Python自定義對象轉Json
同樣可以通過自定義方式,將Python自定義類型的對象轉化為json字元串。
import json
#自定義類
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
#將對象轉換為Python內置類型的字典
def to_dict(self):
return {
"name": self.name,
"age": self.age,
"gender": self.gender
}
#自定義類型對象
person = Person("Tom", 18, "male")
#將Python自定義類型的對象轉化為Python內置類型的字典
python_dict = person.to_dict()
#將Python內置類型的字典轉化為json字元串
json_str = json.dumps(python_dict)
print(json_str)
#輸出結果:{"name": "Tom", "age": 18, "gender": "male"}
六、Json的高級操作
json模塊還提供了一些高級的操作,例如:
- 使用ensure_ascii=False參數輸出為中文字元串。
- 使用sort_keys參數將鍵按字典序排列。
- 使用default關鍵字參數指定一個函數,將不可序列化類型的對象轉化為可序列化的對象。
import json
#自定義類
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def to_dict(self):
return {
"name": self.name,
"age": self.age,
"gender": self.gender
}
#自定義類型對象
person = Person("Tom", 18, "male")
#使用sort_keys參數將字典按照鍵的字典序排列
json_str = json.dumps(person.to_dict(), sort_keys=True)
print(json_str)
#輸出結果:{"age": 18, "gender": "male", "name": "Tom"}
原創文章,作者:WKPE,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/136512.html
微信掃一掃
支付寶掃一掃