我在打开一个非常基本的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"
}
]
}
非常感谢任何帮助,谢谢!
答案 0 :(得分:0)
我很确定您的test1.json
文件包含一个byte order mark。将encoding
参数用于open()
function。使用文件的实际编码;如果我只能猜测 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\SO3\61667193.py
{'Days': [{'Price': '1.61', 'Date': '04-04-13'}, {'Price': '1.61', 'Date': '04-11-13'}]}
注意:您可以使用以下function by ivan_pozdeev 检测真实编码/ BOM:
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