Reading a text file back to the dictionary using json.loads

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

$python scriptTweet.py > output.txt 

The original output returned by the script was a dictionary that was written to a text file.

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

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

This error appears:

  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 do I convert the contents of output.txt to a dictionary again?

+6
source share
1 answer

'tweetfile.read()' is the 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 json read :

 with open("output.txt") as tweetfile: pyresponse = json.load(tweetfile) 
+9
source

Source: https://habr.com/ru/post/944876/


All Articles