extract each 'thing' from json file using python for later use

Viewed 63

I have JSON file stored in an S3 bucket with the following format (there are more objects, this is just a snippet)

[    
    {
        "uuid": "1597c163-6fbf-4f46-8ff6-1e9eb4f07e34",
        "organisation": "org",
        "device_vendor": "bitgear",
        "device_type": "Air",
        "client_id": "2"
    },
    {
        "uuid": "cde2107e-8736-47de-9e87-2033c3063589",
        "organisation": "abc",
        "device_vendor": "bitgear",
        "device_type": "Air",
        "client_id": "1"
    }
]

I am wanting to write a python code which reads each 'thing' out of the JSON. E.g. uuid = cde2107e-8736-47de-9e87-2033c3063589

I have the following code to access the S3 bucket and read the JSON data

s3 = boto3.resource('s3')
client = boto3.client('s3')
bucket = 'data'
key = 'config.json'
obj = s3.Object(bucket, key)
data = obj.get()['Body'].read().decode('utf-8')
json_data = json.loads(data)

I'm just not sure how to extract each thing in a way that I can then generate dynamically for example

MQTT_TOPIC = organisation + ‘/’ + device_vendor + ‘/’ device_type
CERTIFICATION_PATH = BUCKET + ‘/’ organisation + ‘/’ uuid
1 Answers

The neatest way is probably to use the format method with keyword arguments to extract the values you want from each dictionary:

for d in json_data:
    MQTT_TOPIC = "{organisation}/{device_vendor}/{device_type}".format(**d)
    CERTIFICATION_PATH = "{}/{organisation}/{uuid}".format(bucket, **d)
Related