首页 > 解决方案 > 无法将 json.dumps 与 with python 语句一起使用

问题描述

当我运行此代码时:

with open(f"{station_id}.json", "w+") as json_file_2:
    for hourly_json_raw in json_raw['hourly']['data']:
        hourly_json_raw['centroid_id'] = station_id
        hourly_json_raw['s3_key'] = s3_key
        json.dump(hourly_json_raw, json_file_2)
    json.dumps(json_file_2)

我有错误:

TypeError:“TextIOWrapper”类型的对象不是 JSON 可序列化的。

这是因为json_file_2有一个格式io.TextIOWrapper。但是,我看不到如何解决我的问题:

  1. 使用空 JSON 文件(with 行)
  2. 将这个 json_file 迭代地添加到 for 循环中
  3. 最后转储最终结果。

标签: pythonjson

解决方案


也许你的意思是:

with open(f"{station_id}.json", "w+") as json_file_2:
    for hourly_json_raw in json_raw['hourly']['data']:
        hourly_json_raw['centroid_id'] = station_id
        hourly_json_raw['s3_key'] = s3_key
        json.dump(hourly_json_raw, json_file_2)
with open(f"{station_id}.json", 'r') as f:
    json_for_S3 = f.read()

# Now write json_for_S3 to S3

推荐阅读