0

I have an issue opening a pretty basic json file just as a test and I am getting the following output:

\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)

Here is the python code:

import json

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

print(data)

Here is the test.json contents:

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

Any help much appreciated, thank you!

1 Answers1

0

I'm pretty sure that your test1.json file contains a byte order mark. Use the encoding parameter for open() function. Use actual encoding of your file; if I can only guess UTF-8, use encoding='utf-8-sig' as follows:

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)

Output: D:\Python\SO3\61667193.py

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

Note: You can detect real encoding/BOM using the following 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
JosefZ
  • 28,460
  • 5
  • 44
  • 83