首页 > 解决方案 > 覆盖 df.to_json 文件

问题描述

我正在使用 Python 构建一个实时 Twitter 情绪分析网络。我希望将分析结果存储在 json 格式文件中,以用作执行的每次搜索的历史数据。如何覆盖一个文件中的所有搜索数据?数据最初是临时存储在 Pandas 数据框中的,所以我将其转换为 json 中的数组

headings = ("Tweet", "Sentimen")
data = list(zip(tweets['tweet_text'], sentiment))

df = pd.DataFrame(data, columns=['Tweet', 'Sentimen'])
df.to_json(r'Export_DataFrame6.json', orient='records', indent=4)

a_file = open("Export_DataFrame6.json", "r")
json_object = json.load(a_file)
d = json_object[0]
d['Tweet'] = "Testing"
d['Sentimen'] = "Negative"
a_file = open("Export_DataFrame6.json", "w")
json.dump(json_object, a_file)
a_file.close()

更新代码:

 headings = ("Tweet", "Sentimen")
data = list(zip(tweets['tweet_text'], sentiment))

df = pd.DataFrame(data, columns=['Tweet', 'Sentimen'])
df.to_json(r'Export_DataFrame6.json', orient='records', indent=4)

a_file = open("Export_DataFrame6.json", "r")
json_object = json.load(a_file)
a_file.close()

d = json_object[0]
d['Tweet'] = tweets['tweet_text']
d['Sentimen'] = sentiment
a_file = open("Export_DataFrame6.json", "w")
json.dump(json_object, a_file)
a_file.close()

错误:TypeError:Series 类型的对象不是 JSON 可序列化的

标签: pythonarraysjsonpandasdataframe

解决方案


我认为你被困在这条线上:

d = json_object[0]

因为您认为您有一个 json 对象但没有,并且当您尝试使用 [0] 时会收到错误消息。没有看到json文件,这是一个粗略的猜测。

你能这样打开你的文件吗?

with open('Export_DataFrame6.json', 'rb') as f:
    json_object = f.read().decode('utf-8')

然后尝试

d = json_object[0]

or 

d = json.loads(json_object)[0]

推荐阅读