JSON加载的JSON文件问题

时间:2019-03-08 21:49:50

标签: python json python-3.x

我有一个充满json文件的目录,所有文件的格式都与.json文件相同。我正在遍历目录中的每个文件以访问json数据,但是当我尝试加载数据时出现错误。

for json_file in file_list:
with open(backup_folder.joinpath(json_file), 'r') as f:
    json_loaded_data = json_file.load(f)

运行此代码块将返回:

AttributeError                       Traceback (most recent call last)
in 
      1 for json_file in file_list:
      2     with open(backup_folder.joinpath(json_file), 'r') as f:
----> 3         json_loaded_data = json_file.load(f)
      4 
      5         date = json_loaded_data['tradeDate']

AttributeError: 'str' object has no attribute 'load'

示例json文件如下所示:

{
"settlements": [
    {
        "month": "MAR 19",
        "open": "2.650",
        "high": "2.744",
        "low": "2.638",
        "last": "2.647",
        "change": "+.059",
        "settle": "2.642",
        "volume": "225,563",
        "openInterest": "250,706"
    }
}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

json_file只是一个包含文件名的字符串。尝试以下方法:

with open(backup_folder.joinpath(json_file), 'r') as f:
    json_loaded_data = json.load(f)