導讀
本文[1]示範如何使用 Python 的 json.load() 和 json.loads() 方法從檔案和字元串中讀取 JSON 資料。使用 json.load() 和 json.loads() 方法,您可以将 JSON 格式的資料轉換為 Python 類型,這個過程稱為 JSON 解析。Python 内置子產品 json 提供了以下兩種解析 JSON 資料的方法。
要從 URL 或檔案解析 JSON,請使用 json.load()。要解析包含 JSON 内容的字元串,請使用 json.loads()。
JSON parsing
文法
我們可以使用 load 和 loads() 方法進行許多 JSON 解析操作。首先,了解它的文法和參數,然後我們逐一介紹它的用法。
load()
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
loads()
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
參數
所有參數在兩種方法中具有相同的含義。
json.load() 用于從檔案中讀取 JSON 文檔,json.loads() 用于将 JSON 字元串文檔轉換為 Python 字典。
- fp
用于讀取文本檔案、二進制檔案或 JSON 檔案的檔案指針。
- object_hook
是可選函數,将使用任何對象文字解碼的結果調用。
- object_pairs_hook
是一個可選函數,将使用任何對象文字的結果調用,該對象文字是用有序的對清單解碼的。
- parse_float
是可選參數,但如果指定,将使用要解碼的每個 JSON 浮點數和整數的字元串調用。
- parse_int
如果指定,它将使用要解碼的每個 JSON int 的字元串調用。預設情況下,這等同于 int(num_str)。
json.load
json.load() 從檔案中讀取 JSON 資料并将其轉換為字典。使用 json.load() 方法,我們可以從文本、JSON 或二進制檔案中讀取 JSON 資料。 json.load() 方法以 Python 字典的形式傳回資料。然後我們使用這個字典來通路和操作我們的應用程式或系統中的資料。
json.load() 和 json.loads() 方法在解碼時使用轉換表,參考如下
- 解析轉換表
JSON Python object dict array list string str number (int) int number (real) float true True false False null None
例子
現在,我正在讀取硬碟上的“developer.json”檔案。此檔案包含以下 JSON 資料。
developer.json
- 讀取代碼
import json
print("Started Reading `JSON` file")
with open("developer.json", "r") as read_file:
print("Converting `JSON` encoded data into Python dictionary")
developer = json.load(read_file)
print("Decoded `JSON` Data From File")
for key, value in developer.items():
print(key, ":", value)
print("Done reading json file")
- 結果
Started Reading `JSON` file
Converting `JSON` encoded data into Python dictionary
Decoded `JSON` Data From File
name : jane doe
salary : 9000
skills : ['Raspberry pi', 'Machine Learning', 'Web Development']
email : [email protected]
projects : ['Python Data Mining', 'Python Data Science']
Done reading json file
key
如果您想直接通路 JSON key 而不是從檔案中疊代整個 JSON,使用以下代碼
import json
print("Started Reading `JSON` file")
with open("developer.json", "r") as read_file:
print("Converting `JSON` encoded data into Python dictionary")
developer = json.load(read_file)
print("Decoding `JSON` Data From File")
print("Printing `JSON` values using key")
print(developer["name"])
print(developer["salary"])
print(developer["skills"])
print(developer["email"])
print("Done reading json file")
- 結果
Started Reading `JSON` file
Converting `JSON` encoded data into Python dictionary
Decoding `JSON` Data From File
Printing `JSON` values using key
jane doe
9000
['Raspberry pi', 'Machine Learning', 'Web Development']
[email protected]
Done reading json file
json.loads
json.loads() 将 JSON 字元串轉換為字典。有時我們會收到字元串格式的 JSON 資料。是以要在我們的應用程式中使用它,需要将 JSON 字元串轉換為 Python 字典。使用 json.loads() 方法,我們可以将包含 JSON 文檔的原生字元串、位元組或位元組數組執行個體反序列化為 Python 字典。
例子
- 參考如下
import json
developerJsonString = """{
"name": "jane doe",
"salary": 9000,
"skills": [
"Raspberry pi",
"Machine Learning",
"Web Development"
],
"email": "[email protected]",
"projects": [
"Python Data Mining",
"Python Data Science"
]
}
"""
print("Started converting `JSON` string document to Python dictionary")
developerDict = json.loads(developerJsonString)
print("Printing key and value")
print(developerDict["name"])
print(developerDict["salary"])
print(developerDict["skills"])
print(developerDict["email"])
print(developerDict["projects"])
print("Done converting `JSON` string document to a dictionary")
- 結果
Started converting `JSON` string document to Python dictionary
Printing key and value
jane doe
9000
['Raspberry pi', 'Machine Learning', 'Web Development']
[email protected]
['Python Data Mining', 'Python Data Science']
Done converting `JSON` string document to a dictionary
嵌套
- 解析和檢索嵌套的 JSON 鍵值。
假設您有一個如下所示的 JSON 資料:
developerInfo = """{
"id": 23,
"name": "jane doe",
"salary": 9000,
"email": "[email protected]",
"experience": {"python":5, "data Science":2},
"projectinfo": [{"id":100, "name":"Data Mining"}]
}
"""
- 嵌套解析參考如下
import json
print("Started reading nested `JSON` array")
developerDict = json.loads(developerInfo)
print("Project name: ", developerDict["projectinfo"][0]["name"])
print("Experience: ", developerDict["experience"]["python"])
print("Done reading nested `JSON` Array")
- 結果
Started reading nested `JSON` array
Project name: Data Mining
Experience: 5
Done reading nested `JSON` Array
有序字典
- 将 JSON 解析為 OrderedDict
正如我們上面讨論的那樣,json.load() 方法的 object_pairs_hook 參數是一個可選函數,它将使用任何對象文字的結果調用,并使用有序的對清單進行解碼。
- 參考如下
import json
from collections import OrderedDict
print("Ordering keys")
OrderedData = json.loads('{"John":1, "Emma": 2, "Ault": 3, "Brian": 4}', object_pairs_hook=OrderedDict)
print("Type: ", type((OrderedData)))
print(OrderedData)
- 結果
Ordering keys
Type: <class 'collections.OrderedDict'>
OrderedDict([('John', 1), ('Emma', 2), ('Ault', 3), ('Brian', 4)])
類型
假設 JSON 文檔包含許多浮點值,并且您希望将所有浮點值四舍五入到兩位小數。在這種情況下,我們需要定義一個自定義函數來執行您想要的任何舍入。我們可以将這樣的函數傳遞給 parse_float kwarg。當然 parse_int kwarg 也是如此。
- 參考如下
import json
def roundFloats(salary):
return round(float(salary), 2)
def salartToDeduct(leaveDays):
salaryPerDay = 465
return int(leaveDays) * salaryPerDay
print("Load float and int values from `JSON` and manipulate it")
print("Started Reading `JSON` file")
with open("developerDetails.json", "r") as read_file:
developer = json.load(read_file, parse_float=roundFloats,
parse_int=salartToDeduct)
# after parse_float
print("Salary: ", developer["salary"])
# after parse_int
print("Salary to deduct: ", developer["leavedays"])
print("Done reading a `JSON` file")
- 結果
Load float and int values from `JSON` and manipulate it
Started Reading `JSON` file
Salary: 9250.542
<class 'float'>
Salary to deduct: 3
Done reading a `JSON` file
參考資料
[1]Source: https://pynative.com/python-json-load-and-loads-to-parse-json/