[Solved] Json files not getting read in VS-Code

I have made my own JSON file:

CuttingData.json (1001 Bytes)

And I am trying to open it with this piece of code:

import json

with open('CuttingData.json') as data_file:    
    data = json.load(data_file)

I am getting this error in VS-Code:

Traceback (most recent call last):
  File "beamer.py", line 4, in <module>
    data = json.load(data_file)
  File "C:\Users\Mick\Anaconda3\lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\Mick\Anaconda3\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Mick\Anaconda3\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Mick\Anaconda3\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I have tested my piece of code with this JSON file:

test.json (307 Bytes)

And that works.

What am i doing wrong, thank you for helping me!

Hey Mick,

Basically your file has got a Byte Order Mark. Python doesn’t like that BOM character (Hex: “EF BB FF”). You don’t really see this character in most editors which makes this error hard to spot.

So what you can do is:

  • create your json file and make sure the BOM character does not exist
  • Read your file specifying utf-8-sig as encoding.

The code below (Python 3.5) will read json files with or without BOM character.

import json

    with open('CuttingData.json', "r", encoding="utf") as data_file:
        data = json.load(data_file)

except Exception as e:
    print("Error: ", e, "\n")
    with open('CuttingData.json', "r", encoding="utf-8-sig") as data_file:
        data = json.load(data_file)


The solution is in the error code, decode the file as utf-8-sig. Using the try, except and printing the exception usually gives a lot of info.

Error:  Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0) 
1 Like

Thank you Mathijs, works like a charm

1 Like