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

标签 python arrays json list object

我需要将一个 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'}]

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

关于python - 将 json 对象发送到函数 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54621477/

相关文章:

Python 导入错误 : No module named datetime

python - 使用 Pandas 将时间序列转换为开始和结束日期

python - plotly : Heatmap color legend i subplot

jquery - 将数组值设置为 jQuery 表单中的隐藏值

javascript - $.GetJson() 无法从本地文件夹加载 JSON 文件

python - 如何在 django 1.6 中使用 django 模板标签 'url'?

python - 如何根据 python 中提供的 0 和 1 矩阵生成矩阵组合?

javascript - 按长度分解字符串,保留单词

javascript - 在 javascript 或 jquery 中,运行函数名称和参数位于 json 对象中的函数的最佳方式是什么?

c# - 反序列化 json