【发布时间】:2019-01-13 17:25:51
【问题描述】:
我正在尝试将返回列表的函数的输出转换为 JSON 对象。
函数输出如下列表 = [b'E28011600000208', b'E28023232083', b'3000948484']
我想创建一个具有以下属性的 JSON 对象:
{"tag": ["E28011600000208", "E28023232083", "3000948484"]}
类似示例中未显示列表项的解码,如果这是解决此问题的方法,我需要帮助。
我调用的函数如下:
reader.read(timeout=500)
执行同步读取,然后返回搜索结果的 TagReadData 对象列表。如果没有找到标签,则列表将为空。
例如:
print(reader.read())
[b'E2002047381502180820C296', b'0000000000000000C0002403']
在我的代码中,我做了以下事情:
tags = reader.read()
data = json.dumps({tag: tags}, separator=(',','b'))
print (data)
我得到错误: raise TypeError(repr(o) + "不是 JSON 可序列化") TypeError: b'3000948484' 不是 JSON 可序列化的
我尝试了下面的解决方案来删除字节串我的代码如下:
tags = reader.read()
tags = list(map(lambda x:x.decode('utf-8'),tags))
data = json.dumps({'tag':tags})
print(data)
我得到错误: AttributeError: 'mercury.TagReadData' 对象没有属性 'decode'
现在的输出是 JSON,但我的 JSON 文件中仍然有 b' 字符串。我有以下代码:
tag = list(map(lambda x: str(x), tag))
data = json.dumps({'tag': tag})
print(data)
代码输出如下:
{"tag": ["b'30000000321'", "b'300000000'"]}
如何删除 b?通过在 python 3.5 中执行 str(x) ,它应该解码字节,但它没有。
【问题讨论】:
-
要获取的json无效,使用jsonlint.com
-
Python 字典键应该是唯一的。为什么不把
tag作为键和值作为列表 -
当然,即使那样我如何将python输入转换为那种类型的JSON结构@MaNKuR
-
@esqew 列表对象没有解码属性,我将如何解码列表中的 b?