python - 从 JSON 文件中获取特定密钥
问题描述
我正在用 Python 制作一个需要用户登录信息的项目。我正在使用 aUserInfo.json
来读取username
和password
值。
这是我的 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
提前致谢!
解决方案
只需使用负载而不是负载。
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 字典。
这是您可以参考的链接
推荐阅读
- swift - 如何将索引映射存储在数组中以用作变量?
- dolphindb - 如何随机获取集群中某个数据节点的名称?
- gremlin - 无法在 Gremlin 查询中使用“as”选择器
- reactjs - propType "value" 不是必须的,但是没有对应的 defaultProps 声明 react/require-default-props
- javascript - player.playVideo 不是函数
- python - 用标签替换熊猫数据框中的值
- celery - Celery-Flower 添加额外的标签
- ios - Swift 使用 API 请求重构嵌套函数
- python - 如何使用 pysnmp 解析 SNMP 表响应中的 OID 数据?
- java - 为什么关于打印语句的okhttp RequestBody错误