【问题标题】:sending json object to function python将json对象发送到函数python
【发布时间】:2019-07-04 09:52:21
【问题描述】:

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

【问题讨论】:

  • 你为什么不直接使用从json.loads()得到的字典?
  • 完成对字典的附加后,我尝试返回整个内容,但只返回 null。抱歉,我的问题打错了,我编辑了它。
  • 您关于“无法将 JSON 对象直接传递给另一个函数”的断言完全错误。 Python 不限制您在函数之间传递任何类型的对象。

标签: python arrays json list object


【解决方案1】:

这看起来像是一个家庭作业问题 - 您应该在问题中明确说明。

我知道不可能将 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'}]

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

【讨论】:

    猜你喜欢
    • 2012-04-26
    • 1970-01-01
    • 2012-12-01
    • 2018-03-21
    • 1970-01-01
    • 2011-05-17
    • 2014-07-04
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多