正在将类似于json的字节数组转换为python dict所有解决方案都不起作用

hsgswve4  于 2021-06-04  发布在  Kafka
关注(0)|答案(1)|浏览(334)
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 dict中。我尝试过解码和执行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}')

谢谢。

eivnm1vs

eivnm1vs1#

首先,使用 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)

谢谢您

相关问题