Python urllib2 : URL에서 JSON 응답 수신
Python을 사용하여 URL을 얻으려고하는데 응답이 JSON입니다. 그러나 내가 달리면
import urllib2
response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
html=response.read()
print html
html은 str 유형이며 JSON이 필요합니다. 응답을 str 대신 JSON 또는 파이썬 사전으로 캡처 할 수있는 방법이 있습니까?
URL이 유효한 JSON 인코딩 데이터를 반환하는 경우 json
라이브러리 를 사용하여 디코딩합니다.
import urllib2
import json
response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)
print data
import json
import urllib
url = 'http://example.com/file.json'
r = urllib.request.urlopen(url)
data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))
print(data)
urllib , Python 3.4 용
HTTPMessage , r.info ()에서 반환
유효성 검사 등에 대해주의를 기울이십시오. 그러나 직접적인 해결책은 다음과 같습니다.
import json
the_dict = json.load(response)
"""
Return JSON to webpage
Adding to wonderful answer by @Sanal
For Django 3.4
Adding a working url that returns a json (Source: http://www.jsontest.com/#echo)
"""
import json
import urllib
url = 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value'
respons = urllib.request.urlopen(url)
data = json.loads(respons.read().decode(respons.info().get_param('charset') or 'utf-8'))
return HttpResponse(json.dumps(data), content_type="application/json")
resource_url = 'http://localhost:8080/service/'
response = json.loads(urllib2.urlopen(resource_url).read())
Python 3 표준 라이브러리 한 줄짜리 :
load(urlopen(url))
# imports (place these above the code before running it)
from json import load
from urllib.request import urlopen
url = 'https://jsonplaceholder.typicode.com/todos/1'
이미 대답 한 것 같지만 여기에 조금 더하고 싶습니다
import json
import urllib2
class Website(object):
def __init__(self,name):
self.name = name
def dump(self):
self.data= urllib2.urlopen(self.name)
return self.data
def convJSON(self):
data= json.load(self.dump())
print data
domain = Website("https://example.com")
domain.convJSON()
Note : object passed to json.load() should support .read() , therefore urllib2.urlopen(self.name).read() would not work . Doamin passed should be provided with protocol in this case http
you can also get json by using requests
as below:
import requests
r = requests.get('http://yoursite.com/your-json-pfile.json')
json_response = r.json()
This is another simpler solution to your question
pd.read_json(data)
where data is the str output from the following code
response = urlopen("https://data.nasa.gov/resource/y77d-th95.json")
json_data = response.read().decode('utf-8', 'replace')
None of the provided examples on here worked for me. They were either for Python 2 (uurllib2) or those for Python 3 return the error "ImportError: No module named request". I google the error message and it apparently requires me to install a the module - which is obviously unacceptable for such a simple task.
This code worked for me:
import json,urllib
data = urllib.urlopen("https://api.github.com/users?since=0").read()
d = json.loads(data)
print (d)
참고 URL : https://stackoverflow.com/questions/13921910/python-urllib2-receive-json-response-from-url
'code' 카테고리의 다른 글
Java EE 6 대 Spring 3 스택 (0) | 2020.09.11 |
---|---|
선택적 콜백을위한 JavaScript 스타일 (0) | 2020.09.11 |
iOS 13에서 다크 모드 변경 비활성화 (0) | 2020.09.11 |
WPF의 링크 버튼 (0) | 2020.09.11 |
void 포인터를 삭제하는 것이 안전합니까? (0) | 2020.09.11 |