Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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对象时出错_Python_Json_Twitter - Fatal编程技术网

在Python中打开JSON对象时出错

在Python中打开JSON对象时出错,python,json,twitter,Python,Json,Twitter,我对处理JSON对象很陌生。因此,我的程序保存了一些tweet和JSON对象。存储部分看起来像: class MyListener(StreamListener): def on_data(self, data): try: with open('Saved data/' + filename + '.json', 'a') as outfile: outfile.write(data) return True e

我对处理JSON对象很陌生。因此,我的程序保存了一些tweet和JSON对象。存储部分看起来像:

class MyListener(StreamListener):

def on_data(self, data):
    try:
        with open('Saved data/' + filename + '.json', 'a') as outfile:
            outfile.write(data)
            return True
    except BaseException as e:
        print('Error on_data: %s' % str(e))
    return True

def on_error(self, status):
    print(status)
    return True

if stream:
    twitter_stream = Stream(auth, MyListener())
    twitter_stream.filter(track=[tracking_string])
它生成一个json对象,其中包含一些没有任何空行的tweet等等(签入记事本)

开口部分如下所示:

with open('saved data/' + filename + '.json', 'r') as infile:
    for line in infile:
        tweet = json.loads(line)
        tokens = preprocess(tweet['text'])
        print('mark')
只打印一次“标记”。但是在第二次迭代中,我在“tweet=json.loads(line)”中得到了一个错误

似乎到达文件中的第2行有问题,但我真的不明白为什么

提前感谢

保存到json:

json_text = json.dumps(your_dictionary, sort_keys=True, indent=4)

with open(filename, 'w') as json_file:
    json_file.write(json_text)
阅读json:

with open(filename, 'r') as json_file:
    text = json_file.read()
dictionary = json.loads(text)

为什么要逐行读取文件?

行的内容是什么
print
for
行之后打印它,这样您就可以看到有问题的数据。
line
刚刚第一次打印出来,它包含一条tweet。我得到了与之前相同的错误,第二次迭代中没有打印行,即使我将
print(line)
放在
load()
之前。这意味着您在第一行
中得到错误,或者第二行
为空。尝试类似于
print('Current line:',line)
printing'Current line:'第二次迭代,然后出现错误。然后第二行为空。你确定每一行都包含一个有效的JSON字符串吗?我不能这样加载。这可能是因为不同的推特有不同的字典吗?
with open(filename, 'r') as json_file:
    text = json_file.read()
dictionary = json.loads(text)