Search code examples
pythonpython-3.xgoogle-custom-search

How to find value in JSON result from Google custom search in Python


I am successfully returning google search results using custom search engine in JSON. The following is just an example.

https://1drv.ms/t/s!AhueqKzeEHo90Wavbff2U-D8xLmN

As you can see in the JSON, I have operated and appended 4 searches. So JSON contains 4 array elements. What I am trying to do is to find all occurrences of "Dataseet" string in "title" and if found any, print all "link" of the hits.

I have tried many different ways. The last one was

with open('data.json') as f:
    data = json.load(f)

json_str = json.dumps(data)
resp = json.loads(json_str)

list1 = resp[0]['items']
for item in list1:
    if item['title'] in "Datasheet"
        print(item[0]['link'])

This doesn't work at all but I am looking for something similar (algorithm wise). Thanks


Solution

  • try with this code :

    import json
    
    with open('data.json',"r") as f:
        data = json.load(f)
    
    json_str = json.dumps(data)
    resp = json.loads(json_str)
    
    list1 = resp[0]['items']
    for item in list1:
        if item['title'] == "Datasheet":
            print(item['link'])
    

    output :

    https://www.vishay.com/docs/88503/1n4001.pdf
    http://www.vishaypg.com/doc?63012
    https://www.vishay.com/docs/29049/ntcle100.pdf
    https://www.vishay.com/doc?88392