Python Forum

Full Version: Python beginner needs json help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a device that I recieve json messages from and for some reason, finding the keys works on one message but not another. The code worked fine when the keys were real strings as in text labels "Output Pressure" but when they changed to numeric ids "1126" my trouble began.

The snippit of json data that parses fine:
{'sentOn': 1724331308071, 'metrics': {'3280': 82, '3288': 64, '3266': 0, '3287': 225, '3265': 0, '3286': 225, .........

The code snippit is below:
       MsgData = json.loads(message.payload)
        Log.info(MsgData)
        if 'metrics' in MsgData:  #make sure there is data
            s = MsgData['metrics']
            for item in TagList:    "this gets gets tagId's from a list  - keys to find and use from MsgData
                key = str(item['tagId'])    #added str here because it was
                if key in s:
                     rest of code.......
Json message that "if key in s" will never find the keys.
{'sentOn': 1724331309518, 'metrics': {'1183': 255, '1182': 255, '1181': 11, '1180': 15, '1212': 30,..........

The tagId's come from a json I load from a disk file:
It looks like this snippit:

"tagId": "3276", "label":"RPM"

When printing some debug info:
Search data packet for TagId:*1183* is never found in the second message.
Search data packet for TagId:*3280* is always found.

I don't see a difference in either payload. Is there something I'm overlooking on why "if key in s" works on one message and not the other, from the same source?

TIA Rick
My guess would be that message never contains "1183". I would print out the keys in message.metrics to verify (print or log message["metrics"].keys()).