【问题标题】:How do I make a correct JSON file format from this tweepy-script?如何从此 tweepy 脚本制作正确的 JSON 文件格式?
【发布时间】:2018-08-24 21:40:26
【问题描述】:

我正在尝试使用 Tweepy 获取搜索查询的 JSON 格式,但有一个问题:我的最终 JSON 文件是任何程序都无法读取的格式,在检查文件后,脚本似乎写入了所有数据没有任何正确的间距(对于 JSON 格式)

所以,我一直在试图寻找问题,但我真的找不到任何与脚本有关的问题。有人知道写作部分有什么问题吗?

这是脚本:

def write_tweets(tweets, filename):
    ''' Function that appends tweets to a file. '''

    with open(filename, 'a') as f:
        for tweet in tweets:
            json.dump([tweet._json], f)
            f.write('\n')

。 . . .

for search_phrase in search_phrases:

    print('Search phrase =', search_phrase)

    ''' other variables '''
    name = search_phrase.split()[0]
    json_file_root = name + '/'  + name
    os.makedirs(os.path.dirname(json_file_root), exist_ok=True)
    read_IDs = False

    # open a file in which to store the tweets
    if max_days_old - min_days_old == 1:
        d = dt.datetime.now() - dt.timedelta(days=min_days_old)
        day = '{0}-{1:0>2}-{2:0>2}'.format(d.year, d.month, d.day)
    else:
        d1 = dt.datetime.now() - dt.timedelta(days=max_days_old-1)
        d2 = dt.datetime.now() - dt.timedelta(days=min_days_old)
        day = '{0}-{1:0>2}-{2:0>2}_to_{3}-{4:0>2}-{5:0>2}'.format(
              d1.year, d1.month, d1.day, d2.year, d2.month, d2.day)
    json_file = json_file_root + '_' + day + '.json'
    if os.path.isfile(json_file):
        print('Appending tweets to file named: ',json_file)
        read_IDs = True

    # authorize and load the twitter API
    api = load_api()

    # set the 'starting point' ID for tweet collection
    if read_IDs:
        # open the json file and get the latest tweet ID
        with open(json_file, 'r') as f:
            lines = f.readlines()
            max_id = json.loads(lines[-1])['id']
            print('Searching from the bottom ID in file')
    else:
        # get the ID of a tweet that is min_days_old
        if min_days_old == 0:
            max_id = -1
        else:
            max_id = get_tweet_id(api, days_ago=(min_days_old-1))
    # set the smallest ID to search for
    since_id = get_tweet_id(api, days_ago=(max_days_old-1))
    print('max id (starting point) =', max_id)
    print('since id (ending point) =', since_id)

Here's a image the JSON file that I can't open.

【问题讨论】:

  • Waaay 代码太多。请发Minimal, complete and verifiable example
  • 对不起!让我裁剪我需要检查的部分!
  • 是什么让您认为“脚本写入所有数据时没有任何正确的间距(对于 Json 格式)”? JSON 的唯一标准是针对文件中的单个 JSON 文档。有些程序和 API 使用多个 JSON 文档的流,但它们都做不同的事情。有些要求您的 JSON 没有非转义的行终止符,并且在每个结束符之后都有一个换行符。或者他们只禁止\r 并要求\r\n\r\n 作为分隔符。或者他们只是假设 JSON 是自定界的(如果您使用旧的“文档”定义,其中顶层必须是对象或数组)。以此类推。
  • 那么,你想把它传递给哪个程序,它需要在一个文件中包含多个 JSON 文档,它在抱怨什么?
  • 这仍然是太多的代码——但现在它显然完全丢失了所有相关的代码。当然很难确切地知道什么是相关的,但是您在询问“写作部分”并且编辑版本中没有json.dump 或其他写作代码……请阅读@roganjosh 链接到的帮助;它解释了你应该和不应该包括的内容。

标签: python json twitter format tweepy


【解决方案1】:

JSON text 是单个 JSON 值。

您的代码正在打开一个文件并多次调用json.dump,将一堆单独的 JSON 文本连接起来,它们之间带有换行符。结果不是 JSON 文本。正如json module 的文档所说:

注意picklemarshal 不同,JSON 不是框架协议,因此尝试使用相同的fp 重复调用dump() 来序列化多个对象> 将导致无效的 JSON 文件。

通常,您想要的是:

  • 将所有这些单独的内容放在一个列表中,并使用单个json.dump 编写该列表。生成的文件看起来与您正在编写的文件非常相似,除了整个文件的括号和值之间的逗号,但它将是合法的 JSON 文本。
  • 将每个内容放在不同的文件中。每一个都是合法的 JSON 文本。

现在,有一些程序、API 等使用“JSON 文本流”* 作为格式,但没有真正的标准,每个人都有不同的规则关于如何组合它们——需要转义行终止符并使用\n 分隔文本;只需要转义 \r 并使用 \r\n\r\n 分隔文本;假设文本是自定界的(加框);等等。要使用其中一种格式,您必须确切地知道它是什么;它不仅仅是“JSON”——事实上,它根本不是 JSON。


* 或者,更常见的是“JSON 文档流”。旧标准将“文档”定义为对象或数组。新标准将“文本”定义为任何 JSON 类型。这意味着文档是自定界的,但文本不是。 (考虑2,后跟3。)

【讨论】:

  • 此脚本用于更新仅在一个文件中包含特定单词的推文数据库...有没有办法解析“json”以便将其作为数据库读取?跨度>
  • @SantiagoGuinand 打开它并在 what 中阅读它?如果您在我的回答中做这两件事中的任何一件,您可以打开它并在任何可以打开和读取任意 JSON 的程序中读取它。使用它“作为数据库”太模糊了,无法帮助您。您想将此代码解析回一个 Python 对象或一堆 Python 对象以再次编写 Python 查询吗?将其存储在特定的文档存储 nosql 数据库中并对其运行查询?将其存储在混合 sql 数据库中的 JSON 格式列中?只是将 JSON 字符串用作键值存储中的无意义文本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2015-06-16
  • 2021-10-08
  • 1970-01-01
  • 2020-11-04
相关资源
最近更新 更多