首页 > 解决方案 > 从 JSON 文件中获取特定密钥

问题描述

我正在用 Python 制作一个需要用户登录信息的项目。我正在使用 aUserInfo.json来读取usernamepassword值。

这是我的 JSON:

{
  "username": "MyUsername",
  "password": "MyPassword"
}

我目前正在使用这个块:

def readJson(filename):
    with open(filename, 'r') as f:
        data = json.loads(f)
    return data


userData = readJson('UserInfo.json')
print(userData['username'])

当我尝试username从 JSON 中读取密钥时。我收到以下错误:

TypeError: the JSON object must be str, bytes or byte array, not TextIOWrapper

提前致谢!

标签: pythonjson

解决方案


只需使用负载而不是负载。

def readJson(filename):
with open(filename, 'r') as f:
    data = json.loads(f)
return data


userData = readJson('UserInfo.json')
print(userData['username'])

原因是

  • json.load() 方法(“load”中没有“s”)用于从文件中读取 JSON 编码数据并将其转换为 Python 字典。

  • json.loads() 方法,用于将有效的 JSON 字符串解析为 Python 字典。

这是您可以参考的链接


推荐阅读