【问题标题】:Geting specific key from JSON File [closed]从 JSON 文件中获取特定密钥 [关闭]
【发布时间】:2020-09-09 10:12:20
【问题描述】:

我正在用 Python 制作一个需要用户登录信息的项目。我正在使用UserInfo.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'])

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

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

提前致谢!

【问题讨论】:

  • 应该是data = json.load(f).json.loads 会将字符串加载为json。
  • data = json.loads(f.read())
  • 很抱歉这是我的愚蠢错误。我在运行它之前没有保存文件,所以它返回了完整的 JSON。

标签: python json


【解决方案1】:
def readJson(filename):
    with open(filename, 'r') as f:
        data = json.loads(f.read())
    return data


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

使用f.read() 将为您提供内容字符串而不是文件对象。

【讨论】:

    【解决方案2】:

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

    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 字典。

    这里是link,你可以参考

    【讨论】:

      【解决方案3】:

      我找到了问题。

      我只是在运行之前没有保存文件,所以它返回了完整的 JSON。当前区块运行良好。

      【讨论】:

      • 即使文件保存正确,它仍然无法正常工作——看我的回答
      • 是的,这就是我现在使用的。
      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 2015-03-23
      • 1970-01-01
      相关资源
      最近更新 更多