【问题标题】:Error while reading JSON file with Python使用 Python 读取 JSON 文件时出错
【发布时间】:2020-04-01 17:18:53
【问题描述】:

我在使用 python 的 json 模块读取 JSON 文件时遇到错误,我无法理解出了什么问题。以下是我的文件和代码供您参考:

json.load(files_lst[1])

错误:

AttributeError: 'str' 对象没有属性 'read'

在阅读了几个答案后,我也尝试了:

json.loads(files_lst[1])

但我收到以下错误:

JSONDecodeError:预期值:第 1 行第 1 列(字符 0)

这里有什么问题?非常感谢您的帮助

>>> files_lst
['All_Transcripts/x3021_10.50.48.111_04-04-2019.json',
 'All_Transcripts/x5363_09.33.36.955_08-27-2019.mp3.json',
 'All_Transcripts/x3580_11.35.53.462_05-13-2019.json',
 'All_Transcripts/x4342_08.55.01.523_08-01-2019.json',
 'All_Transcripts/x9496_15.26.32.382_05-21-2019.json',
 'All_Transcripts/x5374_08.38.15.692_06-17-2019.json',
 'All_Transcripts/x4342_13.43.57.128_03-21-2019.json']

【问题讨论】:

    标签: json python-3.x


    【解决方案1】:

    json.load 接受打开的文件描述符。所以你应该这样称呼它:

    json.load(open(files_lst[1]))
    

    json.loads 接受 json 作为字符串。所以你应该这样称呼它:

    json.loads(open(files_lst[1]).read())
    

    【讨论】:

    • 您好 Nadav,感谢您的回答,但我仍然遇到同样的错误 JSONDecodeError: Expecting value: line 2 column 1 (char 1)
    • 我无法从这里判断您的问题是什么,因为我不知道您是否使用了json.loadjson.loads,以及文件的内容是什么。如果您附上更新后的代码和错误行的内容,我可能会判断它是否是错误,或者 json 的格式是否无效。
    猜你喜欢
    • 2020-10-11
    • 2019-04-27
    • 2021-01-27
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2021-09-02
    相关资源
    最近更新 更多