skip to Main Content

I have the following json data in a file that I am trying to read in python but I am getting this error. What am I doing wrong?

[
    {
        "name": "Alex C",
        "age": 2,
        "city": "Houston"
    },
    {
        "name": "John G",
        "age": 40,
        "city": "Washington"
    },
    {
        "name": "Bala T",
        "age": 22,
        "city": "Bangalore"
    }
]

Here is my code:

JFile = "JData.json"
F = open(JFile, "w")
try:
    proc = subprocess.Popen([MyCMD], shell=True, encoding='utf-8', stdout=F)
except Exception as ex:
    print("ERROR: CMD Failed....", ex)
F.close()
try:
    with open(JFile, 'r', encoding='utf-8') as J:
        JData = json.loads(J.read())
except json.decoder.JSONDecodeError as e:
    print("invalid json", e)

When I try to run this I get this error:

invalid json Expecting value: line 1 column 1 (char 0)

4

Answers


  1. Chosen as BEST ANSWER

    Actually, the json file was not yet created when I was trying to read in the code. I had to add proc.wait() to resolve my issue.

    JFile = "JData.json"
    F = open(JFile, "w")
    try:
        proc = subprocess.Popen([MyCMD], shell=True, encoding='utf-8', stdout=F)
        proc.wait()
    except Exception as ex:
        print("ERROR: CMD Failed....", ex)
    F.close()
    try:
        with open(JFile, 'r', encoding='utf-8') as J:
            JData = json.loads(J.read())
    except json.decoder.JSONDecodeError as e:
        print("invalid json", e)


  2. what does JFile look like? is it a relative path to the file containing your json object?

    1. try using the full path (don’t forget the file extension).
    2. make sure you that the python interpreter has permission to read that file.
    Login or Signup to reply.
  3. The error
    Expecting value: line 1 column 1 (char 0)
    is thrown when json.load receives an empty string. Have you double checked if the file you’re trying to read contains what you think it does and is in the correct directory? Assuming a file containing a valid JSON, your code should work.

    Login or Signup to reply.
  4. That error suggests the interpreter thinks your data is not valid JSON, despite the fact that the sample you provided is valid JSON. The code you provided works as intended in my local interpreter (Windows 10, Python 3.9.5, standard json library).

    I would double check that the JFile variable is in fact pointing at the file you think it is and that there is no additional data in the file before your JSON (leading whitespace should be acceptable). If that checks out I would try re-saving your file to ensure it really is utf-8 encoded or try reading it without explicitly setting encoding='utf-8' in your code. I think an encoding mismatch would throw a different error but nothing is obviously wrong so it’s worth checking.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search