2016-09-15 59 views
1

我流数据和数据蟒蛇Twitter的API数据被保存到一个JSON文件这样处理与CSV或JSON

with open('filename.json', 'a') as f: 
    f.write(data) 

现在我想读作进一步的分析数据。要简单地在另一个程序中使用json文件,我能做的最简单的事情就是。

import json 
with open('D:\Devotion of time\Data\paralympics.json') as f: 
data= json.load(f) 
or 
data= json.loads(f.read()) 

在这两种情况下,我收到以下错误: -

c:\python27\lib\json\__init__.pyc in load(fp, encoding, cls, object_hook,      
parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 
276   parse_float=parse_float, parse_int=parse_int, 
277   parse_constant=parse_constant,           
object_pairs_hook=object_pairs_hook, 
278   **kw) 
279 
280 

c:\python27\lib\json\__init__.pyc in loads(s, encoding, cls, object_hook,  
parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 
324    parse_int is None and parse_float is None and 
325    parse_constant is None and object_pairs_hook is None and not 
kw): 
326   return _default_decoder.decode(s) 
327  if cls is None: 
328   cls = JSONDecoder 

c:\python27\lib\json\decoder.pyc in decode(self, s, _w) 
367   end = _w(s, end).end() 
368   if end != len(s): 
369    raise ValueError(errmsg("Extra data", s, end, len(s))) 
370   return obj 
371 

ValueError: Extra data: line 3 column 1 - line 107 column 1 (char 13127 - 394133) 

如果我切换到别的东西像这样

data = [] 
with open('file') as f: 
for line in f: 
    data.append(json.loads(line)) 

然后我得到AttributeError的:“海峡'object has no attribute'read' also some time ValueError:没有JSON对象可以被解码

我搜索了解决方案,但没有任何帮助。 我也尝试用Pandas(pd.read_json())读取它,但同样的问题。我想对数据做什么,就是换成一个csv文件,或者如果它是json,那么试着以某种方式轻松使用它。数据看起来像this

所以如何处理这个?我应该改变程序还是别的什么?或者更好的建议来处理twitter数据。*

使用Python27,win10,tweepy。

回答

1

您的文件不包含单个JSON对象,而是每行中包含多个JSON对象。你可以解析每一行如下:

with open('t.txt', 'r') as f: 
    res = [] 
    for line in f: 
     if line.strip() != '': # The sample file also has empty lines 
      res.append(json.loads(line)) 
+0

谢谢,看起来这工作。 –