2016-01-31 27 views
11

Làm cách nào để phân tích cú pháp phản hồi api json bằng python? Tôi hiện có này:Python 3 Nhận và phân tích cú pháp JSON API

import urllib.request 
import json 

url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' 

def response(url): 
    with urllib.request.urlopen(url) as response: 
     return response.read() 

res = response(url) 
print(json.loads(res)) 

Tôi nhận được lỗi này: Lỗi Loại: đối tượng JSON phải được str, không phải là 'byte'

cách pythonic để đối phó với apis json là gì?

Trả lời

19

Version 1: (làm một pip cài đặt yêu cầu trước khi nhập các mô-đun)

import requests 
r = requests.get(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty') 
print(r.json()) 

Phiên bản 2 : (thực hiện cài đặt pip wget trước khi nhập mô-đun)

import wget 

fs = wget.download(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty') 
with open(fs, 'r') as f: 
    content = f.read() 
print(content) 
3

Tôi thường sử dụng gói requests với gói json. Các mã sau đây sẽ phù hợp với nhu cầu của bạn:

Output

[11008076, 
11006915, 
11008202, 
...., 
10997668, 
10999859, 
11001695] 
+0

Sử dụng yêu cầu thực sự là đơn giản nhất nhất để sử dụng giải pháp này. – ferdy

+0

Tôi đang sử dụng Python 3.5 và đang gặp lỗi: Thuộc tínhLỗi: mô-đun 'yêu cầu' không có thuộc tính 'get' Bất kỳ ý tưởng nào về cách giải quyết vấn đề này? – ClickThisNick

+0

Bạn có thể chưa cài đặt nó - hãy thử chạy 'pip install requests' từ dòng lệnh – gtlambert

13

bạn có thể sử dụng tiêu chuẩn thư viện python3:

import urllib.request 
import json 
url = 'http://www.reddit.com/r/all/top/.json' 
req = urllib.request.Request(url) 

##parsing response 
r = urllib.request.urlopen(req).read() 
cont = json.loads(r.decode('utf-8')) 
counter = 0 

##parcing json 
for item in cont['data']['children']: 
    counter += 1 
    print("Title:", item['data']['title'], "\nComments:", item['data']['num_comments']) 
    print("----") 

##print formated 
#print (json.dumps(cont, indent=4, sort_keys=True)) 
print("Number of titles: ", counter) 

đầu ra sẽ như thế này:

... 
Title: Maybe we shouldn't let grandma decide things anymore. 
Comments: 2018 
---- 
Title: Carrie Fisher and Her Stunt Double Sunbathing on the Set of Return of The Jedi, 1982 
Comments: 880 
---- 
Title: fidget spinner 
Comments: 1537 
---- 
Number of titles: 25 
Các vấn đề liên quan