Geovani Benita
Geovani Benita

Reputation: 115

How to extract specific values from JSON

I need to extract a key and a value from a Json loaded into a public API. Currently mi code extract all the values as lists from my extract_values function. But I need just one camera_id and its correspondent value image every delta minutes. I am having trouble because every get() call returns all the values from the Json.

JSON:

 "items": [
    {
      "timestamp": "2020-07-04T02:00:07+08:00",
      "cameras": [
        {
          "timestamp": "2020-07-04T01:59:27+08:00",
          "image": "https://images.data.gov.sg/api/traffic-images/2020/07/b0e99414-f401-47ab-b7a4-223d83f76a2c.jpg",
          "location": {
            "latitude": 1.27414394350065,
            "longitude": 103.851316802547
          },
          "camera_id": "1501",
          "image_metadata": {
            "height": 240,
            "width": 320,
            "md5": "fd1f8e010c789eb59f105a8017c4170e"
          }
        }, 
...
]

Expected output:

camera_id | Image
1501        https://images.data.gov.sg/api/traffic-images/2020/07/b0e99414-f401-47ab-b7a4-223d83f76a2c.jpg

It should be noted that I've got N endpoint urls from different timestamps. But I only want the samecamera_id with its image property from all my different urls.

My code as far:

#Function to extract parameters from JSON
def extract_values(obj, key):
    #Pull all values of specified key from nested JSON.
    arr = []

    def extract(obj, arr, key):
        #Recursively search for values of key in JSON tree.
        if isinstance(obj, dict):
            for k, v in obj.items():
                if isinstance(v, (dict, list)):
                    extract(v, arr, key)
                elif k == key:
                    arr.append(v)
        elif isinstance(obj, list):
            for item in obj:
                extract(item, arr, key)
        return arr

    results = extract(obj, arr, key)
    return results

def getURLS():

    #Retrieve url from different deltas
    endpoint = "https://api.data.gov.sg/v1/transport/traffic-images"
    data = requests.get(endpoint)
    if (data):
        data = requests.get(endpoint).json()
        cam_list = extract_values(data,'camera_id')#Extract all camera_id values as list
        images_list = extract_values(data,'image') #Extract all images values as list

if __name__ == "__main__":    
    getURLS()

How can I achieve this? Thanks in advance

Upvotes: 0

Views: 1144

Answers (2)

alani
alani

Reputation: 13049

In this example, variable req_camera_id contains the camera_id that you want to match. So you loop over the sub-dictionaries as necessary. But I don't think you need a recursive call in this case.

import requests

req_camera_id = '1501'

endpoint = 'https://api.data.gov.sg/v1/transport/traffic-images'
response = requests.get(endpoint)
if response.status_code == 200:
    data = response.json()
    for item in data['items']:
        for cam in item['cameras']:
            camera_id = cam['camera_id']
            if camera_id == req_camera_id:
                image = cam['image']
                print(f'{camera_id} {image}')

gives:

1501 https://images.data.gov.sg/api/traffic-images/2020/07/4c62761d-450d-4aa1-895f-c16482fa620f.jpg

Upvotes: 1

net
net

Reputation: 116

items is a list of objects. Just iterate over the list of objects and grab the value you need from each object.

cam_ids = []
images = []

for item in items:
    cam_ids.append(item['camera_id'])
    images.appned(item['image'])

Upvotes: 0

Related Questions