【发布时间】:2021-11-26 13:05:37
【问题描述】:
我正在将旧的 Python 2 应用程序转换为使用 amoffat sh 模块的 Python 3。
它通过 sh 命令加载 JSON,该命令已停止工作。
我从 docs 了解到,json.loads 之类的方法不适用于 sh RunningCommand 类的实例,即使它类似于字符串。
但是,我似乎无法获得有效的字符串值!
这是有效的原始代码。
aws = sh.aws
......
data = aws.s3api("list-objects", bucket=s3url.bucket, prefix=s3url.path, max_keys=1)
data.wait()
items = json.loads(data)
但是现在抛出TypeError: the JSON object must be str, bytes or bytearray, not RunningCommand
所以我尝试同时使用bytes 和str,但似乎没有任何效果...
转换为字符串:
....
data.wait()
jsonStr = str(data)
print (type(jsonStr))
print (jsonStr)
items = json.loads(jsonStr)
输出
<class 'str'>
{
"IsTruncated": true,
"Marker": "",
"Contents": [
{
"Key": "a/path/to/object/",
"LastModified": "2021-10-06T10:45:45+00:00",
"ETag": "\"g41d8gd98f10b204g9800998gcf8527e\"",
"Size": 100,
"StorageClass": "STANDARD"
}
],
"Name": "bucket-name",
"Prefix": "a/path/to/object/",
"MaxKeys": 1,
"EncodingType": "url"
}
Traceback (most recent call last):
.....
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
使用标准输出字节:
....
jsonBytes = data.stdout
print (type(jsonBytes))
print (jsonBytes)
items = json.loads(jsonBytes)
输出
<class 'bytes'>
b'\x1b[?1h\x1b=\r{\x1b[m\n "IsTruncated": true,\x1b[m\n "Marker": "",\x1b[m\n "Contents": [\x1b[m\n {\x1b[m\n "Key": "a/path/to/object//",\x1b[m\n "LastModified": "2021-10-06T10:45:45+00:00",\x1b[m\n "ETag": "\\"g41d8gd98f10b204g9800998gcf8527e\\"",\x1b[m\n "Size": 100,\x1b[m\n "StorageClass": "STANDARD",\x1b[m\n }\x1b[m\n ],\x1b[m\n "Name": "idetailaid-demo",\x1b[m\n "Prefix": "a/path/to/object//",\x1b[m\n "MaxKeys": 1,\x1b[m\n "EncodingType": "url"\x1b[m\n}\x1b[m\n\r\x1b[K\x1b[?1l\x1b>'
Traceback (most recent call last):
.....
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
【问题讨论】:
-
我不明白为什么,但
json.loads()声称您的问题中 JSON 数据的字符串版本无效,生成了JSONDecodeError。错误出现在第一个反斜杠转义双引号字符的"ETag"行上。它看起来对我有效,并在我通过在线 JSON 验证器工具运行它时进行了检查——所以我很困惑。也是。 -
是的 - 我也注意到了这一点,但这与我得到的错误不同!所以我打算稍后解决这个问题!目前它认为字符串值为
None,而不是格式错误。很奇怪。
标签: python json python-3.x