Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取python中的JSON文件:ValueError_Python_Json_Twitter_Tweepy - Fatal编程技术网

读取python中的JSON文件:ValueError

读取python中的JSON文件:ValueError,python,json,twitter,tweepy,Python,Json,Twitter,Tweepy,我有一个包含70+k json对象的.txt文件,它是通过从twitter中提取数据并使用以下方法转储到文件中获得的: with open("followers.txt", 'a') as f: for follower in limit_handled(tweepy.Cursor(api.followers, screen_name=account_name).pages()): for user_obj in follower: json

我有一个包含70+k json对象的.txt文件,它是通过从twitter中提取数据并使用以下方法转储到文件中获得的:

with open("followers.txt", 'a') as f:
     for follower in limit_handled(tweepy.Cursor(api.followers, screen_name=account_name).pages()):
         for user_obj in follower:
             json.dump(user_obj._json, f)  
             f.write("\n")  
当我尝试使用以下代码在python中阅读此内容时:

import json
with open('followers.txt') as json_data:
     follower_data = json.load(json_data)
我得到一个错误:

ValueError: Extra data: line 2 column 1 - line 2801 column 1 (char 1489 - 8679498)
当我使用上面相同的代码读取一个测试文件,其中包含一个从原始文件复制的json对象时,它就起作用了。一旦我将第二个json对象添加到此文件中,然后使用上面相同的代码就会出现错误:

ValueError: Extra data: line 2 column 1 - line 2 column 2376 (char 1489 - 3864)

如何读取包含多个json对象的文件

编写JSON时会出现问题。必须编写单个JSON对象,因此也可以加载单个JSON对象。当前,您正在写入多个单独的对象,从而导致错误

稍微修改一下您的编写代码:

json_data = []
with open("followers.txt", 'a') as f:
     for follower in limit_handled(tweepy.Cursor(api.followers, screen_name=account_name).pages()):
         for user_obj in follower:
             json_data.append(user_obj._json)             

     # outside the loops
     json.dump(json_data, f)  

现在,在阅读时,您现有的代码应该可以工作了。你会得到一份字典清单

当然,最好从根本上解决问题:编写一个json并读取它,正如所建议的那样。
但是,如果您已经将多个json对象写入一个文件,则可以尝试使用以下代码来使用已创建的文件:

import json
follower_data = []  # a list of all objects
with open('followers.txt') as json_data:
  for line in json_data:
    follower_data.append( json.loads(line) ) 

假设您在将json对象写入
'flowers.txt'
时没有缩进json对象,那么文件中的每一行都是可以独立解析的json对象。

您没有正确写入,因此无法正确读取。感谢您指出@cᴏʟᴅsᴘᴇᴇᴅ. 我已经更新了我的书写代码。@T-Jay如果你使用了我的答案,那么你应该接受我的答案,伙计;p只是开个玩笑。谢谢,这非常适合加载已经在多个json对象中写入的数据。