【问题标题】:What is the best way to write json objects to a text file and then read them back in?将 json 对象写入文本文件然后将它们读回的最佳方法是什么?
【发布时间】:2015-12-07 00:29:39
【问题描述】:

我正在尝试编写一个服务来读取 twitter 提要流数据,然后将其写入文件。我正在将每个 JSON 结构写入文件中的一行。使用不同的服务,我需要读取文件的每一行并加载 json 结构以进行进一步操作。

我的问题是我可以读取第一行然后 JSON 加载器说其余的不是 JSON 结构。他们看起来很好。不知道发生了什么。

写入文件:

self.output = open(os.path.join(self.outputdir,self.filename,'w')
self.output.write(status + "\n")

阅读文件:

with open(file) as f:
   line = line.replace("\n","")
   tweet = json.loads(line)
   print tweet['text']

raise ValueError("没有 JSON 对象可以被解码") ValueError:无法解码任何 JSON 对象

示例 json 文件: JSON File

JSON File

【问题讨论】:

  • json文件的链接失效了。
  • 由于line.replace("\n",""),您可能无法解码json。

标签: python json tweepy


【解决方案1】:

您的 json 由多个 json 对象和空行组成。 您需要将每一行作为新的 json 对象加载并忽略空行:

>>> with open('streamer.151205-071156.json') as f:
>>>    data = [json.loads(l) for l in f if len(l) > 1]
>>> len(data)
7
>>> print(data[0]['text'])
u'Mnjd \U0001f642\U0001f602 https://t.co/BL5Ezxtt0i'

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2011-03-16
    相关资源
    最近更新 更多