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"
                 }
             ]
}
4
  • 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? Commented Apr 23, 2020 at 9:03
  • I'd type out a fresh JSON file by hand and see what happens. Be sure to check encoding as @AKX suggests. Commented Apr 23, 2020 at 9: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. Commented Apr 23, 2020 at 9:05
  • You could try adding encoding="utf_8_sig" to the open() call. Commented Apr 23, 2020 at 9:09

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

In this case, the following StackOverflow post can be useful for your future PowerShell-related programming: stackoverflow.com/questions/40098771/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.