python-3.x
  • api
  • urllib
  • restful-url
  • 2017-11-13 12 views 1 likes 
    1

    파이썬 3으로 웹 API에서 정보를 얻으려고하는데 오류가 발생합니다.Json에서로드하는 방법?

    import json, urllib.request, requests 
    
    def findLocation(): 
    """returns latlng location value in the form of a list.""" 
    
        send_url = 'http://freegeoip.net/json' 
        r = requests.get(send_url) 
        j = json.loads(r.text) 
        lat = j['latitude'] 
        lon = j['longitude'] 
        return lat, lon 
    
    location = findLocation() 
    print(findLocation()[0]) 
    print(findLocation()[1]) 
    
    def readJsonUrl(url): 
    """reads the Json returned by the google api and converts it into a format 
    that can be used in python.""" 
        page = urllib.request.urlopen(url) 
        data_bytes = page.read() 
        data_str = data_bytes.decode("utf-8") 
        page.close() 
    
        return data_str 
    search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw") 
    
    print(search['website']) 
    

    오류 : 어떤 도움에 감사드립니다

    Traceback (most recent call last): 
        File "google api.py", line 28, in <module> 
        print(search['website']) 
    TypeError: string indices must be integers 
    

    그건 내 코드입니다.

    +0

    업데이트 된 행을 사용하면 다른 오류가 발생합니다. 추적 (가장 최근 통화 마지막) : 파일 "google api.py", 줄 35, 인쇄 (검색 [ '결과']) KeyError : '결과' –

    답변

    1

    readJsonUrl() 사용중인 함수는 JSON이 아닌 문자열을 반환합니다. 따라서 search['website']을 시도하면 문자열의 인덱스가 정수일 수 있기 때문에 실패합니다. 문자열 값을 JSON 객체로 파싱 해보십시오. 이렇게하려면 당신은 DICT에 data_str을 문자열 (DICT하지 형식) 변환해야합니다 여기에 Convert string to JSON using Python

    0

    data_str을 허용 대답을 시도 할 수 있습니다! 코드에이 줄을 추가하면됩니다 : convert_to_dict = json.loads (data_str). 그런 다음 convert_to_dict를 반환하고 완료합니다.

    이 시도 :

    import json, urllib.request, requests 
    
    def findLocation(): 
    
        send_url = 'http://freegeoip.net/json' 
        r = requests.get(send_url) 
        j = json.loads(r.text) 
        lat = j['latitude'] 
        lon = j['longitude'] 
        return lat, lon 
    
    location = findLocation() 
    print(findLocation()[0]) 
    print(findLocation()[1]) 
    
    def readJsonUrl(url): 
    
        page = urllib.request.urlopen(url) 
        data_bytes = page.read() 
        data_str = data_bytes.decode("utf-8") 
        page.close() 
    
        convert_to_dict = json.loads(data_str) # new line 
    
        return convert_to_dict # updated 
    
    
    search = readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw") 
    print(search['your_key']) # now you can call your keys 
    
    0

    당신의 readJsonUrl 기능 STR 객체 대신 DICT 개체를 반환하기 때문에 TypeError: string indices must be integers가에 대한 이유를. json.loads 함수를 사용하면 문자열 개체를 dict 개체로 전송하는 데 도움이됩니다.

    다음과 같은 것을 시도 할 수 있습니다 :

    def readJsonUrl(url): 
        with (urllib.request.urlopen(url)) as page: 
         raw = page.read().decode("utf-8") 
        json_data = json.loads(raw) 
        return json_data 
    
    search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw") 
    
    print(search['results']) 
    

    그것이 도움이되기를 바랍니다.

     관련 문제

    • 관련 문제 없음^_^