Python json 打开基本 json 文件时出现解码错误

Python json decode error when opening a basic json file

我在打开一个非常基本的 json 文件作为测试时遇到问题,我得到以下输出:

\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这里是 python 代码:

import json

with open('test1.json') as f:
    data = json.load(f)

print(data)

这里是test.json内容:

{ "Days" : [
    {
        "Date": "04-04-13",
        "Price": "1.61"
    },
    {
        "Date": "04-11-13",
        "Price": "1.61"
    }  
    ]
}

非常感谢任何帮助,谢谢!

我很确定你的 test1.json 文件包含一个 byte order mark. Use the encoding parameter for open() function. Use actual encoding of your file; if I can only guess UTF-8,使用 encoding='utf-8-sig' 如下:

import json

path_to_file='D:\Python\SO3\data\test1.json'

with open(path_to_file, encoding='utf-8-sig') as f:
    data = json.load(f)

print(data)

输出D:\Python\SO3667193.py

{'Days': [{'Price': '1.61', 'Date': '04-04-13'}, {'Price': '1.61', 'Date': '04-11-13'}]}

注意:您可以检测真正的encoding/BOM使用以下function by ivan_pozdeev:

def detect_by_bom(path,default):
    with open(path, 'rb') as f:
        raw = f.read(4)    #will read less if the file is smaller
    for enc,boms in \
            ('utf-8-sig',(codecs.BOM_UTF8,)),\
            ('utf-16',(codecs.BOM_UTF16_LE,codecs.BOM_UTF16_BE)),\
            ('utf-32',(codecs.BOM_UTF32_LE,codecs.BOM_UTF32_BE)):
        if any(raw.startswith(bom) for bom in boms): return enc
    return default