Json 文件以 b- 开头

Sla*_*a84 1 python sockets json

我正在使用 Json 格式的套接字库从传感器流式传输数据,并尝试解析它并将其加载到数据库中。当我打印流时,我得到以下格式的 Json:

b'[{"metadata":{"timezone":{"location":"Etc/UTC"},"serial_number":"00:07:32:52:09:fc","device_type":"SPIDER"},"timestamp":"2019-08-29T13:53:05.895Z","framenumber":"2290718","tracked_objects":[{"id":2592,"is_at_border":true,"type":"PERSON","position":{"x":233,"y":262,"type":"FOOT","coordinate_system":"PROCESSING_IN_PIXEL"},"person_data":{"height":1728}}]}]'
Run Code Online (Sandbox Code Playgroud)

根据我的研究,前缀 b 代表字节类型。所以当我尝试用下面的代码解析它时:

while True:
    message, address = server_socket.recvfrom(1024)
    message = message.upper()

    # loading json file.
    objs_json = json.loads(message)
    # using if looop to prevent script of trying to to parse data without any object being tracked.
    if "tracked_objects" in objs_json:
        # Parsing json file with json_normalize object
        objs_df = json_normalize(
            objs_json, record_path='tracked_objects',
            meta=[['metadata', 'serial_number'], 'timestamp']
        )
        # Renaming columns
        objs_df = objs_df.rename(
            columns={
                "id": "object_id", "position.x": "x_pos", 
                "position.y": "y_pos", "person_data.height": "height",
                "metadata.serial_number": "serial_number",
                "timestamp": "timestamp"
            }
        )
        # Selecting columns of interest
        objs_df = objs_df.loc[:, ["timestamp", "serial_number", "object_id", "x_pos", "y_pos", "height"]]
        # Writting the data into SQlite db
        objs_df.to_sql('data_object', con=engine, if_exists='append', index=False)
    # In case there is no tracks, print No Tracks in console.
    else:
        print("No Tracks")
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

    Traceback (most recent call last):
  File "/home/pi/ProRail-PMS/Test_Spider2.py", line 20, in <module>
    objs_json = json.loads(message)
  File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 215 (char 214)
Run Code Online (Sandbox Code Playgroud)

但是,如果我将该数据保存到 json 文件中并删除前缀 b,我的解析代码就可以工作。我如何解决这个问题,以便当我从套接字库接收数据时,我希望能够解析它并将其输入数据库?

h4z*_*4z3 6

起初我想评论说它对我有用,但后来我注意到你如何获取消息以及如何处理它:

消除message = message.upper()

>>> message = b'[{"metadata":{"timezone":{"location":"Etc/UTC"},"serial_number":"00:07:32:52:09:fc","device_type":"SPIDER"},"timestamp":"2019-08-29T13:53:05.895Z","framenumber":"2290718","tracked_objects":[{"id":2592,"is_at_border":true,"type":"PERSON","position":{"x":233,"y":262,"type":"FOOT","coordinate_system":"PROCESSING_IN_PIXEL"},"person_data":{"height":1728}}]}]'
>>> json.loads(message)
[{'metadata': {'timezone': {'location': 'Etc/UTC'}, 'serial_number': '00:07:32:52:09:fc', 'device_type': 'SPIDER'}, 'timestamp': '2019-08-29T13:53:05.895Z', 'framenumber': '2290718', 'tracked_objects': [{'id': 2592, 'is_at_border': True, 'type': 'PERSON', 'position': {'x': 233, 'y': 262, 'type': 'FOOT', 'coordinate_system': 'PROCESSING_IN_PIXEL'}, 'person_data': {'height': 1728}}]}]
>>
>>
>>> message = message.upper()
b'[{"METADATA":{"TIMEZONE":{"LOCATION":"ETC/UTC"},"SERIAL_NUMBER":"00:07:32:52:09:FC","DEVICE_TYPE":"SPIDER"},"TIMESTAMP":"2019-08-29T13:53:05.895Z","FRAMENUMBER":"2290718","TRACKED_OBJECTS":[{"ID":2592,"IS_AT_BORDER":TRUE,"TYPE":"PERSON","POSITION":{"X":233,"Y":262,"TYPE":"FOOT","COORDINATE_SYSTEM":"PROCESSING_IN_PIXEL"},"PERSON_DATA":{"HEIGHT":1728}}]}]'
>>> json.loads(message)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 217 (char 216)
>>> message[217:]
b'RUE,"TYPE":"PERSON","POSITION":{"X":233,"Y":262,"TYPE":"FOOT","COORDINATE_SYSTEM":"PROCESSING_IN_PIXEL"},"PERSON_DATA":{"HEIGHT":1728}}]}]'
Run Code Online (Sandbox Code Playgroud)

upper破坏了未加引号的 True 值(因为它是布尔值,而不是字符串)。;)