python - 将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
解决方案
这看起来像一个家庭作业问题 - 你应该在你的问题中说清楚。
我知道不可能将 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'}]
编辑后,我在您的代码中看到了问题。你看到你做了什么吗?
推荐阅读
- vuejs2 - 试图在 ChartJS 中获取点击栏的 _index
- python - 将可变长度张量修剪到最大长度
- java - 如何在字符串变量中获取特定的 Json 值 - Java?
- sql - SQL sum 将列显示为行
- ruby-on-rails - 如何列出所有父对象的所有子对象?
- python - 在 colab 中转发 twint 命令
- php - 我的 Laravel 5.5 应用程序在部署后无法在远程服务器 namecheap VPS 上运行,但在使用 WAMP 的本地服务器上运行良好
- r - 如何使 row_number() 和 quosures 在 R 函数中一起工作?
- c# - 重置定时器(DispatcherTimer)
- autodesk-forge - Autodesk Forge 获取带有标记的屏幕截图