Skip to main content
 首页 » 编程设计

python之将 json 对象发送到函数 python

2025年05月04日19落叶无声

我需要将一个 JSON 对象传递给 python 中的一个单独的函数

import json 
 
userList = [{username: 'userName', email: 'email'}] 
 
listString = json.dumps(userList) 
print(json.loads(listString)) 

这将打印相同的对象:[{username: 'userName', email: 'email'}]

我知道不可能将 JSON 对象直接传递给另一个函数,这就是为什么我要将它变成一个字符串并尝试在新函数中解压它

testFunction(listString) 
 
def testFunction(oldList): 
    print(json.dumps(oldList)) 

这将打印出 [{'username': 'userName', 'email': 'email'}] 但不会让我从新函数返回对象。我需要做什么来解决这个问题?

def testFunction(oldList): 
    newList = json.loads(oldList) 
    # code to append to newList 
 
    return newList 
 
 
Response: null 

请您参考如下方法:

这看起来像是一道作业题 - 你应该在你的问题中说清楚。

I know it isn't possible to pass a JSON object directly to another function

没有“JSON 对象”你有一个包含 python 字典的 python 列表。 json.dumps 将该列表转换为 JSON 字符串,json.loads(string) 获取该字符串并返回 python 列表。

您可以将您的 userList 传递给该函数。或者,如果这是作业并且您需要传递一个 JSON 字符串,您首先使用 json.dumps 将您的列表转换为 JSON 字符串:

import json 
 
userList = [{"username": 'userName', "email": 'email'}] 
 
listString = json.dumps(userList) 
 
def foo(jsonstring): 
  lst = json.loads(jsonstring) 
  lst[0]["username"] = "Alex" 
  return lst 
 
newList = foo(listString) 
 
print(newList) 

输出是:

[{'username': 'Alex', 'email': 'email'}] 

在您编辑后,我发现您的代码中存在问题。你看到你做了什么吗?