【问题标题】:Error while opening JSON-object in Python在 Python 中打开 JSON 对象时出错
【发布时间】:2016-06-06 14:50:48
【问题描述】:

我在使用 JSON 对象方面还是个新手。因此,我的程序将一些推文保存在 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 对象,其中包含一些没有任何空行的推文等(在记事本中检查)。

开头部分是这样的:

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)”处收到错误消息

JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

似乎到达第 1 行时出现问题。 2 在文件中,但我真的不明白为什么。

提前致谢

【问题讨论】:

  • line的内容是什么? printfor 行之后,这样您就可以看到违规数据。
  • line 刚刚被第一次打印出来,它包含一条推文。我遇到了与以前相同的错误,即使我将print(line) 放在loads() 之前,第二次迭代也不会打印行。
  • 这意味着您在第一个line 中遇到错误,或者第二个line 为空。试试print('Current line:', line)
  • printing 'Current line:' 第二次迭代,然后出现错误。
  • 那么第二行是空的。你确定每一行都包含一个有效的 JSON 字符串吗?

标签: python json twitter


【解决方案1】:

保存到 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)

为什么要分行读取文件?

【讨论】:

  • 我无法以这种方式加载。可能是因为不同的推文有不同的字典?
猜你喜欢
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多