我已经在几个不同的方法剔除该数据加载到大熊猫。如果任何人有这些异常的任何建议,这将是非常感谢!在tweet_json.txt和tweet_json.json之间的一些示例中的文件名变化我尝试不同的方法。
with open('tweet_json.json', 'r') as f:
data = json.load(f)
df_3 = pd.DataFrame(data)
结果:JSONDecodeError: Extra data: line 2 column 1 (char 3974)
df_3 = pd.read_json('tweet_json.json', lines = True)
结果:ValueError: Unexpected character found when decoding object value
with open('tweet_json.txt') as file:
status = []
for line in file:
data = json.loads(line)
df_3 = pd.Dataframe(data)
结果:JSONDecodeError: Expecting ',' delimiter: line 1 column 1626 (char 1625)
我唯一的一次远程任何成功使用json.dumps(),但这只是装成一列数据框什么也没有解析,并成为了JSON看起来像一个多层次的字典我根本不知道如何去分离它:
data = []
with open('tweet_json.json') as f:
for line in f:
data.append(json.dumps(line))
df_3 = pd.DataFrame(data)
您可以使用json_normalize或read_json读取JSON文件转换成数据帧。
如果您有嵌套的JSON结构也可以使用from_records功能
这是我解决的方式。我缺少定义列特别要导入的使用地图。我仍然不知道如何做到这导入整个JSON的DF,但这样做我所需要的。
tweets_data = []
tweet_file = open('tweet_json.txt', "r")
for line in tweet_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
tweet_file.close()
tweet_info = pd.DataFrame()
tweet_info['id'] = list(map(lambda tweet: tweet['id'], tweets_data))
tweet_info['retweet_count'] = list(map(lambda tweet: tweet['retweet_count'], tweets_data))
tweet_info['favorite_count'] = list(map(lambda tweet: tweet['favorite_count'], tweets_data))