使用json.loads将文本文件读回字典

时间:2013-05-13 12:39:02

标签: python json

我用我的Python脚本输出了一个使用以下内容访问实时twitter推文到文件output.txt:

$python scriptTweet.py > output.txt

最初,脚本返回的输出是一个写入文本文件的字典。

现在我想使用output.txt文件来访问存储在其中的推文。但是,当我使用此代码使用json.loads()将output.txt中的文本解析为python字典时:

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

弹出此错误:

    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

我应该如何将文件output.txt的内容再次转换为字典?

1 个答案:

答案 0 :(得分:10)

'tweetfile.read()'是您看到的字符串。你想调用这个函数:

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

或使用json.load直接阅读,并在json本身上read tweetfile

with open("output.txt") as tweetfile:
    pyresponse = json.load(tweetfile)
相关问题