0

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))
  • OK, so [edit](https://stackoverflow.com/posts/67092954/edit) the question to show what you've tried and explain what didn't work and somebody will help you fix it. We don't write code on request, but we help you with what you've tried. – hardillb Apr 14 '21 at 14:30
  • You need to explain what you mean by "it doesn't work at all". Also include a little more context, I assume all that is in the `on_message()` callback? You need to show the whole function and where/how you defined `cache` and `topics` – hardillb Apr 14 '21 at 15:38
  • https://stackoverflow.com/a/17154492/504554 – hardillb Apr 15 '21 at 15:40

0 Answers0