Search code examples
pythonjsonijson

Python ijson on badly organized json


I'm trying to get data out of Kontakt.io's MQTT broker. This is the format it's providing, including the leading b' and trailing '

    b'[
        {
            "timestamp":1530121741,
            "sourceId":"OaBW9",
            "trackingId":"t7J5",
            "rssi":-57,
            "proximity":"IMMEDIATE",
            "scanType":"BLE",
            "deviceAddress":"ea:21:88:b3:d2:5f"
        },
        {
            "timestamp":1530121741,
            "sourceId":"OaBW9",
            "trackingId":"t7J5",
            "rssi":-68,
            "proximity":"IMMEDIATE",
            "scanType":"BLE",
            "deviceAddress":"ea:21:88:b3:d2:5f"
        }
    ]'

Seeing as there's no organization in the JSON other than in blocks, how can I actually pull the data from it using keys?

I've tried:

    test = ijson.items(str(msg.payload), 'rssi.item')
    columns = list(test)
    print(columns[0])

As seen in many examples, but I can't figure out how to make it work without "burrowing" into JSON trees (as in the earth.europe.etc.item examples seen everywhere). Should I be trying to get rssi.item using array indexes or something like that? Should I trim the json's " b' " and trailing " ' "?

I don't work with Python very often, so I feel a little out in the water with this.


Solution

  • Solved with help by Konstantin and juanpa.arrivillaga's answers combined. Used import json not ijson

        test = json.loads(msg.payload.decode())
        print([x.get('rssi') for x in test])