dict到json over loop python

时间:2016-02-09 02:10:36

标签: python json

我使用Twitter的流式api使用Tweepy提取推文并将其写入json文件。到目前为止,我已成功提取推文并使用file write将其写入json文件,但当我尝试使用json package时,我会收到错误,如下面的代码所示。

 def on_data(self, data):
    #to convert data to dict format since twitter data is in string format
    json_data = json.loads(data)
    try:
        with open('twitter_data.json','ab') as f:
                if 'limit' in json_data.keys():
                    return True
                else:
                    #This method works
                    #f.write(json.dumps(json_data)+ "\n")
                    #this one does not as it concatenates dict i.e different dict are not separated by a comma
                    json.dump(json_data,f)
                    return True
    except BaseException as e:
        print e
        logging.debug('Error %s',e)
        return True

1 个答案:

答案 0 :(得分:1)

您获得了正确的数据但没有行分隔符...因此请自行添加

import json
with open('deleteme', 'a') as fp:
    json.dump('data', fp)
    fp.write('\n')