将 byte json-like 数组转换为 python 字典。所有解决方案均无效

Converting byte json-like array to a python dict. All solutions did not work

b'{"BusinessEntityID": 23, "Title": null, "FirstName": "Mary", "MiddleName": "E", "LastName": "Gibson", "Suffix": null, "JobTitle": "Marketing Specialist", "PhoneNumber": "531-555-0183", "PhoneNumberType": "Work", "EmailAddress": "mary0@adventure-works.com", "EmailPromotion": 0, "AddressLine1": "3928 San Francisco", "AddressLine2": null, "City": "Everett", "StateProvinceName": "Washington", "PostalCode": "98201", "CountryRegionName": "United States", "AdditionalContactInfo": null}'

我正在使用 Kafka 使用上述内容,我想将其提取到 python 字典中。 我已经尝试解码并执行 json.loads 但触发了此错误 Expecting value: line 1 column 1 (char 0)

这也不起作用。这是我的代码:

try: 
    while True:
        msg = consumer.poll(1.0)
        if msg is None:
            print('...')
        elif msg.error() is None:
            msg_string = ''.join(map(chr, msg.value()))
            print(type(msg_string)) # <class 'str'>
            record = json.loads(msg_string) # ERROR: Expecting value: line 1 column 1 (char 0
            print(record)
        elif msg.error() is not None:
            print(f'Msg Error {msg.error()}')
except Exception as e:
    print(f'ERROR: {e}')

谢谢。

首先,使用a.decode('utf-8')将其转换为普通字符串,然后使用json.loads将其转换为JSON对象

a = b'{"BusinessEntityID": 23, "Title": null, "FirstName": "Mary", "MiddleName": "E", "LastName": "Gibson", "Suffix": null, "JobTitle": "Marketing Specialist", "PhoneNumber": "531-555-0183", "PhoneNumberType": "Work", "EmailAddress": "mary0@adventure-works.com", "EmailPromotion": 0, "AddressLine1": "3928 San Francisco", "AddressLine2": null, "City": "Everett", "StateProvinceName": "Washington", "PostalCode": "98201", "CountryRegionName": "United States", "AdditionalContactInfo": null}'

j = json.loads(a.decode('utf-8'))
print(j)

谢谢