Python Forum
Python beginner needs json help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python beginner needs json help
#1
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
Reply
#2
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()).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Split json into separate json based on node value CzarR 1 9,807 Jul-08-2022, 07:55 PM
Last Post: Larz60+
  difficulties to chage json data structure using json module in python Sibdar 1 2,719 Apr-03-2020, 06:47 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020