2

I have a json file in the same directory with my app where I have saved some names and passwords. When a user clicks a button, I am trying to retrieve these data and compare it with the input he gave. However, I get an encoding error JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I tried adding errors='ignore' and change encoding without success.

My login function which opens the json file:

def login(name,password):
    with open('data.json', 'r', encoding='utf-8', errors='ignore') as f:
        try:
            data = json.loads(f.read())
            #data = json.load(f) didnt work also
            print(data)

        except ValueError:  # includes simplejson.decoder.JSONDecodeError
            print('Decoding JSON has failed')
            return False

        f.close()

And this is in my django app

def test(request):
    if request.method == 'POST':
        given_name = request.POST.get('name', None)
        given_password = request.POST.get('pass', None)
        # do something with user
        if login(given_name, given_password):
            about(request)
        else:
            test_home(request)
         ....

Json file:

{
    "names": [
        "test",
    ],
    "passwords": [
        "test",
    ]
}
Jordan
  • 525
  • 1
  • 4
  • 19
  • This brings up another error: TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper' which doesnt show up if i use json.load(f) – Jordan Oct 05 '19 at 14:46
  • Your `json` file is probably empty or you are using a wrong path to open it. – Abhyudai Oct 05 '19 at 14:47
  • Do you have these weird characters in your 'data.json'? https://stackoverflow.com/questions/38883476/how-to-remove-those-x00-x00 – chaooder Oct 05 '19 at 14:48
  • It isnt empty and its in the same folder so why would the path cause problems? – Jordan Oct 05 '19 at 14:49
  • @chaooder no i dont – Jordan Oct 05 '19 at 14:49
  • sorry, I meant `json.load(f)`, not `json.loads(f)`! see [here](https://stackoverflow.com/questions/39719689/what-is-the-difference-between-json-load-and-json-loads-functions) ;-) – FObersteiner Oct 05 '19 at 14:50
  • @MrFuppes yes i undrestood it but that also didnt work – Jordan Oct 05 '19 at 14:52
  • 2
    looking at your `json` content, there are commas after the strings in "names" / "passwords" lists. `json` therefore expects more list elements... try removing the commas, worked for me. – FObersteiner Oct 05 '19 at 15:01
  • @MrFuppes that's exactly the issue. JSON doesn't tolerate the trailing commas at the end of the list. – John Szakmeister Oct 05 '19 at 15:04

1 Answers1

3

try modifying the json file as I pointed out in the comment;

{
    "names": [
        "test"
    ],
    "passwords": [
        "test"
    ]
}

now you should get

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

data
Out[5]: {'names': ['test'], 'passwords': ['test']}
FObersteiner
  • 22,500
  • 8
  • 42
  • 72