python - 无法将 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
。但是,我看不到如何解决我的问题:
- 使用空 JSON 文件(with 行)
- 将这个 json_file 迭代地添加到 for 循环中
- 最后转储最终结果。
解决方案
也许你的意思是:
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
推荐阅读
- c# - 使用 xunit 在 .NET Core 集成测试中获取数据库连接字符串
- javascript - Amazon chrome 扩展事件未触发
- c - 是否可以在C中提取char指针数组的大小
- windows - 让 dll 从其调用 .exe 导入符号
- android - 如何在 Retrofit 2 中解析下面的 json?
- python - 使用python查找由空格分隔的字符串中存在的数字的总和
- dart - 有没有办法找到对象的范围?
- javascript - document.getElementsByClassName 给我未定义的值
- ios - Xcode 10 GM 中的未知类和 NSUnknownKeyException
- ios - Safari 是否控制在 iOS 上的非 Safari 浏览器中读取 cookie 的方式?