Trong bài viết này, chúng tôi sẽ học cách phân tích phản hồi JSON bằng thư viện yêu cầu. Ví dụ: chúng tôi đang sử dụng thư viện Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}1 để gửi cuộc gọi RESTful Get đến máy chủ và đổi lại, chúng tôi đang nhận được phản hồi ở định dạng JSON, hãy để xem cách phân tích dữ liệu JSON này trong Python.parse a JSON response using the requests library. For example, we are using a Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}1 library to send a RESTful GET call to a server, and in return, we are getting a response in the JSON format, let’s see how to parse this JSON data in Python.
Chúng tôi sẽ phân tích phản hồi của JSON vào từ điển Python để bạn có thể truy cập dữ liệu JSON bằng các cặp giá trị khóa. Ngoài ra, bạn có thể xuất bản JSON đẹp ở định dạng có thể đọc được.
Phản hồi của yêu cầu GET chứa thông tin chúng tôi gọi nó là tải trọng. Chúng ta có thể tìm thấy thông tin này trong thân thông báo. Sử dụng các thuộc tính và phương thức của Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}2 để xem tải trọng ở các định dạng khác nhau.
Chúng tôi có thể truy cập dữ liệu tải trọng bằng ba phương thức sau của mô -đun yêu cầu.
- Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}3 Được sử dụng để truy cập dữ liệu tải trọng ở định dạng byte thô.
- Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}4: Được sử dụng để truy cập dữ liệu tải trọng ở định dạng chuỗi.
- Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}5 Được sử dụng để truy cập dữ liệu tải trọng ở định dạng nối tiếp JSON.
Nội dung phản hồi JSON
Mô -đun yêu cầu cung cấp bộ giải mã JSON tích hợp, chúng tôi có thể sử dụng nó khi chúng tôi đang xử lý dữ liệu JSON. Chỉ cần thực hiện Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}5, và đó là nó. Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}5 Trả về phản hồi JSON ở định dạng từ điển Python để chúng tôi có thể truy cập JSON bằng các cặp giá trị khóa.requests module provides a builtin JSON decoder, we can use it when we are dealing with JSON data. Just execute Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}5, and that’s it. Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}5 returns a JSON response in Python dictionary format so we can access JSON using key-value pairs.
Bạn có thể gặp lỗi 204 trong trường hợp giải mã JSON không thành công. ________ 15 & nbsp; làm tăng một ngoại lệ trong kịch bản sau.
- Phản hồi không chứa bất kỳ dữ liệu nào.
- Phản hồi chứa JSON không hợp lệ
Bạn phải kiểm tra Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}9 hoặc print("Print each key-value pair from JSON response") for key, value in jsonResponse.items(): print(key, ":", value)0 trước khi phân tích JSON vì cuộc gọi thành công đến Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}5 không cho thấy sự thành công của yêu cầu.
Trong trường hợp lỗi HTTP 500, một số máy chủ có thể trả về đối tượng JSON trong phản hồi không thành công (ví dụ: chi tiết lỗi với HTTP 500). Vì vậy, bạn nên thực hiện Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}5 sau khi kiểm tra Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}9 hoặc kiểm tra print("Print each key-value pair from JSON response") for key, value in jsonResponse.items(): print(key, ":", value)0.
Hãy cùng xem ví dụ về cách sử dụng phản hồi.json () và nội dung parse json.
Trong ví dụ này, tôi đang sử dụng httpbin.org để thực hiện cuộc gọi nhận. httpbin.org & nbsp; & nbsp; là một dịch vụ web cho phép các yêu cầu kiểm tra và trả lời dữ liệu về yêu cầu. Bạn có thể sử dụng dịch vụ này để kiểm tra mã của bạn.
import requests from requests.exceptions import HTTPError try: response = requests.get('//httpbin.org/get') response.raise_for_status() # access JSOn content jsonResponse = response.json() print("Entire JSON response") print(jsonResponse) except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}')Output::
Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}Lặp lại phản ứng JSON
Hãy cùng xem cách lặp lại tất cả các cặp có giá trị khóa JSON từng người một.
print("Print each key-value pair from JSON response") for key, value in jsonResponse.items(): print(key, ":", value)Output:
Print each key-value pair from JSON response args : {} headers : {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'} origin : 49.35.214.177, 49.35.214.177 url : //httpbin.org/getTruy cập khóa JSON trực tiếp từ phản hồi bằng tên khóa
print("Access directly using a JSON key name") print("URL is ") print(jsonResponse["url"])Đầu ra
URL is //httpbin.org/getTruy cập khóa JSON lồng nhau trực tiếp từ phản hồi
print("Access nested JSON keys") print("Host is is ") print(jsonResponse["headers"]["Host"])Output::
Access nested JSON keys URL is httpbin.orgBài tập và câu đố Python
Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.
- Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
- Mỗi bài tập chứa 10 câu hỏi
- Mỗi bài kiểm tra chứa 12-15 mcq
Bạn có thể sử dụng phản hồi JSON trực tiếp làm từ điển:
import requests res = requests.get('//reqres.in/api/users?page=2') print(f'Total users: {res.json().get("total")}')Hoặc bạn có thể giữ nội dung JSON làm từ điển:
json_res = res.json()Và từ biến từ điển print("Print each key-value pair from JSON response") for key, value in jsonResponse.items(): print(key, ":", value)5 này, bạn có thể trích xuất bất kỳ giá trị nào bạn chọn
Entire JSON response {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': '//httpbin.org/get'}0Sự chú ý bởi vì đây là một từ điển, bạn nên để mắt đến chính tả chính và trường hợp, tức là 'tổng số' không giống như 'tổng số' Because this is a dictionary, you should keep your eye on the key spelling and the case, i.e. 'total' is not the same as 'Total'