从UTF-8编码的字节字符串读取JSON数据

时间:2018-10-27 08:52:54

标签: python json python-3.x python-3.6

我有一个脚本,该脚本将JSON UTF-8编码的Byte字符串发送到套接字。 (一个github项目:https://github.com/alios/raildriver)。现在,我正在编写需要读取传入数据的python脚本。现在,我可以接收数据并将其打印到终端了。使用以下脚本:https://www.binarytides.com/code-telnet-client-sockets-python/

输出:

data = '{"Current": 117.42609405517578, "Accelerometer": -5.394751071929932, "SpeedometerKPH": 67.12493133544922, "Ammeter": 117.3575210571289, "Amp": 117.35590362548828, "Acceleration": -0.03285316377878189, "TractiveEffort": -5.394751071929932, "Effort": 48.72163772583008, "RawTargetDistance": 3993.927734375, "TargetDistanceBar": 0.9777777791023254, "TargetDistanceDigits100": -1.0, "TargetDistanceDigits1000": -1.0}'

问题是我找不到如何读取JSON数组。例如,读取"Ammeter"并将其值117.357521057289返回到新变量。

所有数据都在变量data中被接收

我现在拥有的代码:

decodedjson = data.decode('utf-8')
dumpedjson = json.dumps(decodedjson)
loadedjson = json.loads(dumpedjson)

能帮我吗?

1 个答案:

答案 0 :(得分:4)

您正在编码为JSON,然后再次解码。立即不编码,删除第二行:

decodedjson = data.decode('utf-8')
loadedjson = json.loads(decodedjson)

如果您使用的是Python 3.6或更高版本,则实际上不必从UTF-8解码,因为json.loads()函数知道如何直接处理UTF编码的JSON数据。同样适用于Python 2:

loadedjson = json.loads(data)

使用Python 3.7进行演示:

>>> data = b'{"Current": 117.42609405517578, "Accelerometer": -5.394751071929932, "SpeedometerKPH": 67.12493133544922, "Ammeter": 117.3575210571289, "Amp": 117.35590362548828, "Acceleration": -0.03285316377878189, "TractiveEffort": -5.394751071929932, "Effort": 48.72163772583008, "RawTargetDistance": 3993.927734375, "TargetDistanceBar": 0.9777777791023254, "TargetDistanceDigits100": -1.0, "TargetDistanceDigits1000": -1.0}'
>>> loadedjson = json.loads(data)
>>> loadedjson['Ammeter']
117.3575210571289