如何將JSON物件作為引數傳遞給Python函式?


可以使用**json.loads()**方法將JSON物件作為引數傳遞給Python函式。我們也可以根據JSON字串的結構將其轉換為Python字典或列表。

JSON物件

考慮將一個JSON物件解析為Python函式。

{
  "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'}}

更新於: 2024年10月14日

8K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.