使用python从json对象获取键

ykejflvf  于 2023-01-08  发布在  Python
关注(0)|答案(2)|浏览(146)

我有这个python脚本,它从一个应用程序接收http post请求,该应用程序以JSON格式发送有效负载封送拆收器。

class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self._set_response()
        self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        #logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
        #       str(self.path), str(self.headers), post_data.decode('utf-8'))

        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
        json_obj = json.loads(post_data)
        packet = json_obj["objectJSON"]
        print(packet)

def run(server_class=HTTPServer, handler_class=S, port=8090):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

有效负载如下所示:

{"applicationID": "3", "applicationName": "loraSmartWatch", "deviceName": "sw2", "devEUI": "xxxxxxx=", "rxInfo": [{"gatewayID": "xxxxxxxx=", "time": "2023-01-06T23:16:42.647816Z", "timeSinceGPSEpoch": "1357082202.647s", "rssi": -82, "loRaSNR": 9.2, "channel": 7, "rfChain": 1, "board": 0, "antenna": 0, "location": {"latitude": 44.40421, "longitude": 25.94427, "altitude": 70, "source": "UNKNOWN", "accuracy": 0}, "fineTimestampType": "NONE", "context": "sdk1XA==", "uplinkID": "xxxxxxxxxxxx==", "crcStatus": "CRC_OK"}], "txInfo": {"frequency": 868500000, "modulation": "LORA", "loRaModulationInfo": {"bandwidth": 125, "spreadingFactor": 7, "codeRate": "4/5", "polarizationInversion": false}}, "adr": true, "dr": 5, "fCnt": 543, "fPort": 10, "data": "vb29vQKAAMhf92EK", "objectJSON": "{\"Enter Sleep\":\"0\",\"Exit Sleep\":\"0\",\"Low Power\":\"0\",\"Packet\":\"Uplink alerting message\",\"Power Off\":\"0\",\"Remove Device\":\"0\",\"SOS Exit\":\"1\",\"Time Stamp\":\"6:04:24 2022/1/31\",\"Wearing Device\":\"0\"}", "tags": {}, "confirmedUplink": true, "devAddr": "AAETWQ==", "publishedAt": "2023-01-06T23:16:42.869850441Z", "deviceProfileID": "26222709-e2e6-48be-b41b-110c857a3371", "deviceProfileName": "origoED20W"}

从这个有效载荷中,我必须提取这个部分:

"objectJSON": "{\"Enter Sleep\":\"0\",\"Exit Sleep\":\"0\",\"Low Power\":\"0\",\"Packet\":\"Uplink alerting message\",\"Power Off\":\"0\",\"Remove Device\":\"0\",\"SOS Exit\":\"1\",\"Time Stamp\":\"6:04:24 2022/1/31\",\"Wearing Device\":\"0\"}"

并且从这部分我必须将每个键与它自己的值分开,例如:

"Enter Sleep":"0"
"Packet":"Uplink alerting message"

我遇到了一个颠簸这样做,任何帮助将不胜感激。谢谢!

zbwhf8kr

zbwhf8kr1#

要将字符串从objectJSON解析为字典,可以使用eval:

packet = "{\"Enter Sleep\":\"0\",\"Exit Sleep\":\"0\",\"Low Power\":\"0\",\"Packet\":\"Uplink alerting message\",\"Power Off\":\"0\",\"Remove Device\":\"0\",\"SOS Exit\":\"1\",\"Time Stamp\":\"6:04:24 2022/1/31\",\"Wearing Device\":\"0\"}"

parsed = eval(string)

print(parsed)
# {'Enter Sleep': '0', 'Exit Sleep': '0', 'Low Power': '0', 'Packet': 'Uplink alerting message', 'Power Off': '0', 'Remove Device': '0', 'SOS Exit': '1', 'Time Stamp': '6:04:24 2022/1/31', 'Wearing Device': '0'}

print(parsed['Packet'])
# Uplink alerting message
kulphzqa

kulphzqa2#

你可以这样解析它:

import json

payload = json.loads(payload)

object_json = payload['objectJSON']

object_dict = json.loads(object_json)

for key, value in object_dict.items():
    print(f'"{key}":"{value}"')

输出:

"Enter Sleep":"0"
"Exit Sleep":"0"
"Low Power":"0"
"Packet":"Uplink alerting message"
"Power Off":"0"
"Remove Device":"0"
"SOS Exit":"1"
"Time Stamp":"6:04:24 2022/1/31"
"Wearing Device":"0"

希望能有所帮助

相关问题