문제

url에서 정보를 조작하려고합니다.나는 그것을 성공적으로 열고 그 내용을 읽을 수 있습니다.그러나 내가 정말로하고 싶은 것은 내가 원하지 않는 모든 물건을 던지고, 내가 지키고 싶은 물건을 조작하는 것입니다.

문자열을 DICT로 변환하는 방법이 있으므로 반복 할 수 있습니까?아니면 그대로 그대로 파싱해야합니까 (str 유형)

from urllib.request import urlopen

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

print(response.read()) # returns string with info
.

도움이 되었습니까?

해결책

response.read()를 인쇄하면 b가 String (예 : b'{"a":1,..)에 전립 처리되었음을 알아 차렸다."B"는 바이트를 나타내며 처리중인 객체 유형에 대한 선언으로 사용됩니다.이후, json.loads('string')를 사용하여 문자열을 Dict로 변환 할 수 있음을 알았으며 바이트 유형을 문자열 유형으로 변환해야했습니다.UTF-8 decode('utf-8')에 대한 응답을 디코딩 하여이 작업을 수행했습니다.일단 문자열 유형에 있으면 내 문제가 해결되었고 dict를 쉽게 반복 할 수있었습니다.

이것이 가장 빠르게 또는 대부분의 'pythonic'이 일을 쓰는 방법인지 모르지만 그것은 작동하고 항상 최적화와 개선의 나중에 시간을 초과합니다!내 솔루션의 전체 코드 :

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key
.

다른 팁

Python의 요청 라이브러리를 대신 사용할 수도 있습니다.

import requests

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'    
response = requests.get(url)    
dict = response.json()
.

이제 파이썬 사전처럼 "Dict"를 조작 할 수 있습니다.

json는 파이썬 3의 유니 코드 텍스트와 함께 작동합니다 (JSON 형식 자체는 유니 코드 텍스트 측면에서만 정의됩니다) 따라서 HTTP 응답에서 수신 된 바이트를 디코딩해야합니다. r.headers.get_content_charset('utf-8') 문자 인코딩을 가져옵니다.

#!/usr/bin/env python3
import io
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r, \
     io.TextIOWrapper(r, encoding=r.headers.get_content_charset('utf-8')) as file:
    result = json.load(file)
print(result['headers']['User-Agent'])
.

여기에서 io.TextIOWrapper를 사용할 필요가 없습니다.

#!/usr/bin/env python3
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r:
    result = json.loads(r.read().decode(r.headers.get_content_charset('utf-8')))
print(result['headers']['User-Agent'])
.

Python 3.4에서는 일이 변경되었다고 생각합니다.이것은 나를 위해 일했습니다 :

print("resp:" + json.dumps(resp.json()))
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top