首页 > 解决方案 > 将json对象发送到函数python

问题描述

我需要将 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

标签: pythonarraysjsonlistobject

解决方案


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

我知道不可能将 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)

输出是:

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

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


推荐阅读