T1960CT
T1960CT

Reputation: 437

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.

Upvotes: 0

Views: 186

Answers (2)

T1960CT
T1960CT

Reputation: 437

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])

Upvotes: 0

Konstantin
Konstantin

Reputation: 547

Try this one:

import json 

a = 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"
        }
    ]'''


b = json.loads(a)
print([x.get('rssi') for x in b])

Output:

[-57, -68]

Upvotes: 1

Related Questions