1

I want to open a JSON file using Python in my project, but I constantly get the following error:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This is the code:

import json
with open("../data.txt") as json_file:
    data = json.load(json_file)

I have a really simple text file with JSON formatted data in it. This is the data.txt file:

{
    "data":  [
                 {
                     "day":  "22/04/2020 15:35",
                     "viewcount":  "1"
                 },
                 {
                     "day":  "22/04/2020 20:51",
                     "viewcount":  "2"
                 }
             ]
}
Emre Sevinç
  • 8,211
  • 14
  • 64
  • 105
Arne Hus
  • 55
  • 11
  • 3
    Are you absolutely, positively sure there are no extra characters at the start of that file? Also, are you sure it's been saved using the UTF-8 encoding, not e.g. UTF-8 with a Byte Order Marker? – AKX Apr 23 '20 at 09:03
  • I'd type out a fresh JSON file by hand and see what happens. Be sure to check encoding as @AKX suggests. – amitchone Apr 23 '20 at 09:05
  • Yes, I copied the exact file. There is definetly nothing at the start of that file. The only thing i'm not sure about is: I make that file with a powershell script, maybe it doesn't save it in the correct encoding. – Arne Hus Apr 23 '20 at 09:05
  • You could try adding `encoding="utf_8_sig"` to the `open()` call. – AKX Apr 23 '20 at 09:09

2 Answers2

2

I've tried your source code and the visible JSON data as is, it runs with no problems at all.

I'd suggest checking the contents of file in binary form, e.g. by using a utility such as hexdump to see how it begins:

$ hexdump data.txt 
0000000 0a7b 2020 2020 6422 7461 2261 203a 5b20                                                                                                                                                
0000010 200a 2020 2020 2020 2020 2020 2020 2020                                                                                                                                                
0000020 2020 0a7b 2020 2020 2020 2020 2020 2020
...

Or use file utility to check the encoding as described in the following post: https://unix.stackexchange.com/questions/11602/how-can-i-test-the-encoding-of-a-text-file-is-it-valid-and-what-is-it

Emre Sevinç
  • 8,211
  • 14
  • 64
  • 105
1

The python code was not the problem. The file was not saved in UTF-8 encoding, this was the problem.

Arne Hus
  • 55
  • 11
  • In this case, the following StackOverflow post can be useful for your future PowerShell-related programming: https://stackoverflow.com/questions/40098771/changing-powershells-default-output-encoding-to-utf-8 – Emre Sevinç Apr 23 '20 at 09:20