bjw*_*hip 1 python arrays json list object
我需要将JSON对象传递给python中的单独函数
import json
userList = [{username: 'userName', email: 'email'}]
listString = json.dumps(userList)
print(json.loads(listString))
Run Code Online (Sandbox Code Playgroud)
这将打印相同的对象: [{username: 'userName', email: 'email'}]
我知道不可能将JSON对象直接传递给另一个函数,这就是为什么我将其转换为字符串并尝试在新函数中解压缩它的原因
testFunction(listString)
def testFunction(oldList):
print(json.dumps(oldList))
Run Code Online (Sandbox Code Playgroud)
这将打印出来,[{'username': 'userName', 'email': 'email'}]但不会让我从新函数中返回对象。我需要做什么来解决这个问题?
def testFunction(oldList):
newList = json.loads(oldList)
# code to append to newList
return newList
Response: null
Run Code Online (Sandbox Code Playgroud)
小智 5
这看起来像是一个作业问题-您应该在问题中明确说明。
我知道不可能将JSON对象直接传递给另一个函数
没有“ 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)
Run Code Online (Sandbox Code Playgroud)
输出为:
[{'username': 'Alex', 'email': 'email'}]
Run Code Online (Sandbox Code Playgroud)
编辑后,我在您的代码中看到了问题。你看到你做了什么吗?