Home > other >  getting keys from json object using python
getting keys from json object using python

Time:01-07

I have this python script which receives http post requests from an application which sends the payload marshaler as 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()

The payload looks like this:

{"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"}

From this payload i must extract this part:

"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\"}"

And from this part i must separate each key with its own value, for example:

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

I ran into a bump on doing this and any help will be appreciated. Thanks!

CodePudding user response:

To parse your string from objectJSON to a dictionary you can use 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

CodePudding user response:

You can parse it like this :

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}"')

Output :

"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"

Hope it helps

  • Related