繁体   English   中英

不能在with python语句中使用json.dumps

[英]Cannot use json.dumps with the with python statement

当我运行此代码时:

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. 反复在for循环中将此json_file附加
  3. 最后转储最终结果。

也许您的意思是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM