I would like to generate a python dict from a mqtt topic and payload.
Like if i receive this payload: 85
from this topic: data/nb200s/050100227/cm
I would like to add or update this to a python dict like this:
pythonDict = {}
pythonDict["data"]["nb200s"]["050100227"]["cm"] = 85
Is there a good way to do this?
Thanx a lot!
Here is what i have now but it doesn't work at all:
m_decode = ""
try:
m_decode = msg.payload.decode("utf-8", "ignore")
except Exception as e:
m_decode = msg.payload
topics = msg.topic.split("/")
dataStr = cache.get("mqttJson")
if dataStr:
data = json.loads(dataStr)
else:
data = dict()
tLen = len(topics)
if tLen == 1:
data[topics[0]] = m_decode
elif tLen == 2:
data[topics[0]][topics[1]] = m_decode
elif tLen == 3:
data[topics[0]][topics[1]][topics[2]] = m_decode
elif tLen == 4:
data[topics[0]][topics[1]][topics[2]][topics[3]] = m_decode
elif tLen == 5:
data[topics[0]][topics[1]][topics[2]][topics[3]][topics[4]] = m_decode
else:
return
cache.set(json.dumps(data, sort_keys=True))