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:Drpcli 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)
CodePudding user response:
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.
CodePudding user response:
what does JFile
look like? is it a relative path to the file containing your json object?
- try using the full path (don't forget the file extension).
- make sure you that the python interpreter has permission to read that file.
CodePudding user response:
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.