如何將 JSON 物件作為引數傳遞給 Python 函式?
將 JSON 物件作為引數傳遞給 Python 函式可以透過使用 **json.loads()** 方法來實現。我們還可以將 JSON 字串轉換為 Python 字典或列表,這取決於其結構。
JSON 物件
考慮一個要作為 Python 函式解析的 JSON 物件。
{
"name":"Rupert",
"age": 25,
"desig":"developer"
}
使用 json.loads()
在將 JSON 物件作為引數傳遞給函式之前,需要將其轉換為 Python 物件。可以使用 Python 的 **json** 模組中的 **json.loads()** 方法來實現。
涉及的步驟
-
**匯入 json 模組**: 首先匯入 **'json'** 模組,該模組包含處理 JSON 資料的工具。
-
**建立 JSON 字串**: 定義要使用的 JSON 字串。
-
**使用 json.loads() 轉換**: 使用 'json.loads()' 將 JSON 字串轉換為 Python 字典或列表。
-
**傳遞給函式**: 將轉換後的 Python 物件作為引數傳遞給你的函式。
示例
在下面的示例程式碼中,**'json.loads()'** 函式解析 JSON 物件 **('strng')** 並將其轉換為 Python 字典。
# Importing json module
import json
# Defines JSON string
json_string = '{"name":"Rupert", "age": 25, "desig":"developer"}'
print (type(json_string))
# Define function which processes a JSON string
# Converting the JSON string into a Python dictionary
def func(strng):
a =json.loads(strng)
print (type(a))
# Iterating the dictionary
for k,v in a.items():
print (k,v)
print (dict(a))
func(json_string)
輸出
<class 'str'>
<class 'dict'>
name Rupert
age 25
desig developer
{'name': 'Rupert', 'age': 25, 'desig': 'developer'}
使用 JSON 反序列化
將 JSON 字串轉換回 Python 物件的過程稱為 JSON 反序列化。通常,此方法用於處理以 JSON 格式傳輸或儲存的資料。
示例
在示例程式碼中,**'json.loads()'** 函式用於將 JSON 字串反序列化為 Python 物件。生成的 Python 物件 **'python_obj'** 將是一個表示 JSON 字串結構的字典。
import json
# JSON string
json_string = '{"name": "John", "age": 30, "is_student": false, "courses": ["Math", "Science"], "address": {"city": "New York", "state": "NY"}}'
# Deserialize JSON string to Python object
python_obj = json.loads(json_string)
print(python_obj)
輸出
{'name': 'John', 'age': 30, 'is_student': False, 'courses': ['Math', 'Science'], 'address': {'city': 'New York', 'state': 'NY'}}
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP