【发布时间】:2018-07-05 16:12:09
【问题描述】:
我是 CS 的一年级学生,正在尝试调试一个简单的 Python 脚本。
脚本正在尝试解析 JSON 文件的目录,也就是 AWS 存储桶。但是,我无法弄清楚这些错误来自哪里:
import json
import os
from pprint import pprint
jsonDirectory = "/path/to/dir/"
targetRegion = "-insert-region-here"
print("Searching for records with AWS Region: " + targetRegion)
print("")
for filename in os.listdir(jsonDirectory):
print("Reading: " + filename)
data = json.dumps(open(jsonDirectory + filename))
for i in range(len(data["Records"])):
if data["Records"][i]["awsRegion"] == targetRegion:
print("---------------------------")
print("Record #" + str(i))
print("Username: " + data["Records"][i]["userIdentity"] ["userName"])
print("Event name: " + data["Records"][i]["eventName"])
print("Event time: " + data["Records"][i]["eventTime"])
print("---------------------------")
print("")
print("Completed reading files.")
错误:
Traceback(最近一次调用最后一次): 文件“/path/to/file.py”,第 13 行,在 数据 = json.dumps(open(jsonDirectory + 文件名)) 转储中的文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py”,第 231 行 返回 _default_encoder.encode(obj) 文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py”,第 199 行,编码 块 = self.iterencode(o, _one_shot=True) 文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py”,第 257 行,在 iterencode 返回 _iterencode(o, 0) 文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py”,第 180 行,默认 o.班级.姓名) TypeError:“TextIOWrapper”类型的对象不是 JSON 可序列化的
【问题讨论】:
-
应该使用
json.load而不是json.dumps -
谢谢!我仍然收到错误:“Traceback(最近一次调用最后一次):文件“/path/of/script.py”,第 13 行,在
data = json.load(open(jsonDirectory + filename)) File “/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py”,第 296 行,在加载返回加载(fp.read(),文件“/Library/Frameworks/Python. framework/Versions/3.6/lib/python3.6/codecs.py",第 321 行,在 decode (result,consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can' t 解码位置 37 中的字节 0xb0:无效起始字节" -
对你有用吗?
-
对糟糕的格式表示抱歉。
-
检查你的文件,你有一个错误,如位置 37 所示
标签: python json debugging error-handling