Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading text file back into a dictionary using json.loads

Tags:

python

json

I piped the output of my Python script which accesses live twitter tweets to a file output.txt using:

$python scriptTweet.py > output.txt

Originally, the output returned by the script was a dictionary which got written to a text file.

Now i want to use the output.txt file to access tweets stored in it. But when i use this code to parse the text in output.txt into a python dictionary using json.loads():

tweetfile = open("output.txt")
pyresponse = json.loads('tweetfile.read()')
print type(pyresponse)

This error pops up:

    pyresponse = json.loads('tweetfile.read()')
  File "C:\Python27\lib\json\__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

How should i convert the contents of file output.txt again into a dictionary?

like image 947
learner123 Avatar asked May 13 '13 12:05

learner123


1 Answers

'tweetfile.read()' is a string as you see it. You want to call this function:

with open("output.txt") as tweetfile:
    pyresponse = json.loads(tweetfile.read())

or read it directly using json.load and let json read on the tweetfile itself:

with open("output.txt") as tweetfile:
    pyresponse = json.load(tweetfile)
like image 77
eumiro Avatar answered Oct 14 '22 10:10

eumiro