first post here.
I've been using Python for a while now, but I'm stuck with a very simple case.
I just want to parse a JSON file with simplejson module: here is the code:
import simplejson
with open('myjsontest.json', 'r') as data_file:
print data_file.read()
session = simplejson.load(data_file, strict=False)
And here is the JSON file named myjsontest.json:
[
{
"Test1": 1,
"Test2": 2,
"Test3": 3,
"Test4": 4
}
]
The JSON file is in the same folder as the python file.
I got this as a result:
[
{
"Test1": 1,
"Test2": 2,
"Test3": 3,
"Test4": 4
}
]
Traceback (most recent call last):
File ".\test.py", line 8, in <module>
session = simplejson.load(data_file, strict=False)
File "C:\Users\Gordon\Anaconda2\lib\site-packages\simplejson-3.8.1-py2.7.egg\simplejson\__init__.py", line 459, in loa
d
use_decimal=use_decimal, **kw)
File "C:\Users\Gordon\Anaconda2\lib\site-packages\simplejson-3.8.1-py2.7.egg\simplejson\__init__.py", line 533, in loa
ds
return cls(encoding=encoding, **kw).decode(s)
File "C:\Users\Gordon\Anaconda2\lib\site-packages\simplejson-3.8.1-py2.7.egg\simplejson\decoder.py", line 370, in deco
de
obj, end = self.raw_decode(s)
File "C:\Users\Gordon\Anaconda2\lib\site-packages\simplejson-3.8.1-py2.7.egg\simplejson\decoder.py", line 400, in raw_
decode
return self.scan_once(s, idx=_w(s, idx).end())
File "C:\Users\Gordon\Anaconda2\lib\site-packages\simplejson-3.8.1-py2.7.egg\simplejson\scanner.py", line 127, in scan
_once
return _scan_once(string, idx)
File "C:\Users\Gordon\Anaconda2\lib\site-packages\simplejson-3.8.1-py2.7.egg\simplejson\scanner.py", line 87, in _scan
_once
raise JSONDecodeError(errmsg, string, idx)
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I think think I may have a problem in my OS/python setup? Python 32b 2.7.11 is installed with Anaconda on a Windows7 64b.
Thanks if you can help.
Once you read
a file, its stream is at the end and cannot be read from anymore. Your code should work if you remove the print data_file.read()
statement, or you .seek()
back to the beginning of the file afterwards.