如何将 Twitter 的 json 对象加载到 Python 中

3
我想将从Twitter API挖掘的JSON加载到Python中。以下是JSON对象的样本:
我想把从Twitter API中挖掘出来的JSON数据加载到Python中。下面是一个JSON对象的示例:
{"created_at":"Mon Apr 22 18:17:09 +0000 2019","id":1120391103813910529,"id_str":"1120391103813910529","text":"On peut dire que la base de cette 8e saison est en place \ud83d\ude4c #GOTS8E2","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":243071138,"id_str":"243071138","name":"Mr B","screen_name":"skeyos","location":"Namur","url":null,"description":null,"translator_type":"none","protected":false,"verified":false,"followers_count":197,"friends_count":1811,"listed_count":6,"favourites_count":7826,"statuses_count":8044,"created_at":"Wed Jan 26 06:49:05 +0000 2011","utc_offset":null,"time_zone":null,"geo_enabled":true,"lang":"fr","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/493833348167770112\/aGLGemZ5_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/493833348167770112\/aGLGemZ5_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/243071138\/1406574068","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"GOTS8E2","indices":[59,67]}],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"fr","timestamp_ms":"1555957029666"}

{"created_at":"Mon Apr 22 18:17:14 +0000 2019","id":1120391124722565123,"id_str":"1120391124722565123","text":"...

我正在尝试以下代码:
with open('tweets.json') as tweet_data:
    json_data = json.load(tweet_data)

但是出现了以下错误:
JSONDecodeError: Extra data: line 3 column 1 (char 2149)

很遗憾,由于JSON对象非常庞大,我无法对其进行太多编辑。我需要找出如何将其读入Python中。任何帮助都将不胜感激!
编辑:下面的代码可以实现该功能:
dat=list()
with open ('data_tweets_E2.json', 'r') as f:
    for l in f.readlines():
        if not l.strip (): # skip empty lines
            continue

        json_data = json.loads (l)
        dat.append(json_data)

每一行都包含一个新的对象,因此请逐行解析它们。如果您正在从字符串中解析,请使用 loads - hingev
请尝试使用我下面的代码,我还帮你处理了DataFrame。你遇到的错误是由于JSON文件语法错误导致的。但是代码是正确的。因此,请尝试使用一个JSON对象并检查您的错误。 - Michal Moravik
3个回答

2

以下是代码。当然,您需要先安装Pandas。如果这个解决方案有帮助,请用绿色对勾标记此答案。

Original Answer翻译成"最初的回答"

import json
import pandas as pd

with open('tweets.json') as json_file:
    data_list = json.load(json_file)

tweet_data_frame = pd.DataFrame.from_dict(data_list)
print(tweet_data_frame)
print(data_list)

你可以看到,print(data_list)会输出一个列表,而print(tweet_data_frame)则输出数据框。
如果你想查看这些变量的类型,使用type()即可:print(type(data_list)).
重要提示:我想告诉你的是,你的JSON文件格式有问题,并且存在许多错误。如果你还有其他的JSON对象,它们需要放在数组中,例如:[{"example":"value"},{"example":"value"}]。你的JSON文件存在错误,请尝试使用其他的JSON文件。

嗨,我现在只有一个列表而不是字典(请参见问题中的编辑)。有没有办法使用列表完成这个任务?或者如果我一开始就能将数据附加到字典中,那也可以,但我不知道该怎么做。 - Thelonious Monk
我尝试了你的代码,但是遇到了相同的JSONDecodeError。这就是为什么我将所有数据附加到列表中的原因。如果有一种方法可以将所有数据加载到字典中而不是列表中,那对我也行。 - Thelonious Monk
@ArtTatum 好的,我已经编辑了我的代码。请尝试使用不同的JSON文件,你会发现你有一个损坏的文件。希望这可以帮到你。如果这是你想要的,请告诉我。 :) - Michal Moravik
1
谢谢,我明白你的意思了。幸运的是,我不需要那些有坏数据的列。 - Thelonious Monk

1
每行都包含一个单独的JSON对象,解析并将它们存储到列表中:
with open('tweets.json', 'r') as tweet_data:
    values = [json.loads(line) for line in tweet_data.readlines() 
              if not line.strip()]

1

每一行都包含一个新的对象,因此请逐行解析它们。

import json

with open ('tweets.json', 'r') as f:
    for l in f.readlines():
        if not l.strip (): # skip empty lines
            continue

        json_data = json.loads (l)
        print (json_data)

谢谢,已经加载完毕。但是当我输入json_data时,只有最后一条推文显示出来。我该如何将所有推文存储在一个对象中?另外,如果我能将json格式转换为数据框就太好了! - Thelonious Monk
每次迭代,json_data 存储一个对象。如果您想要访问它们所有的话,请将它们推入列表或其他数据结构中。 - hingev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接