Search code examples
pythonjsonloopsinstagram-api

Checking whether a JSON dictionary is empty or not and storing in a list


I have an Instagram API which I load into a JSON. The response is coming properly and I am even able to fetch the id from the data received. Then I save it in a python list and put it in an Excel sheet using openpyxl.

Here is the catch. While loading the values, If there is no response from API in case of a deleted instagram account,where the JSON will be empty, I want to store "ACC deleted" in the list.

(NOTE :- I also referred similar questions but didnt get my answer which works.)

Here is the code:

for r in range(1,51):
    var=r,test.cell(row=r,column=1).value
    xy=var[1]
    myopener=Myopener()
    url=myopener.open('https://api.instagram.com/v1/users/search?q='+xy+'&count=1&access_token=641567093.1fb234f.a0ffbe574e844e1c818145097050cf33')

    **beta=json.load(url)
    for item in beta['data']:
        list.append(item['id'])** //*HERE I WANT THE CHANGE*


    for j in range(len(list)):
        for row in sheet.iter_rows(min_row=j+1, max_row=j+1):
            for cell in row:
                cell.value=list[j]
                wb.save('sample.xlsx')

The json Response is this:

{
"meta":  {
"code": 200
},
"data":  [
 {
  "username": "rawhawk_sk",
  "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12724928_109384759877664_1105313598_a.jpg",
  "id": "670907103",
  "full_name": "shwan mcswan"
}
]
}

If the json response is empty like below, how to store "ACC deleted" in the list?

{
"meta":  {
"code": 200
},
"data":  []
} 

Solution

  • You can check if data is empty in your script and if so add a new entry 'ACC deleted' to the list.

    import json
    
    jsons = []
    jsons.append("""{
    "meta":  {
    "code": 200
    },
    "data":  [
     {
      "username": "rawhawk_sk",
      "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12724928_109384759877664_1105313598_a.jpg",
      "id": "670907103",
      "full_name": "shwan mcswan"
    }
    ]
    }
    """)
    
    jsons.append("""{
    "meta":  {
    "code": 200
    },
    "data":  []
    } """)
    
    output_list = []
    
    for txt in jsons:
        beta = json.loads(txt)
        if beta.get('data'):
            for item in beta['data']:
                output_list.append(item['id'])
        else:
            output_list.append('ACC deleted')
    
    print(output_list)