Thông thường, các nhà phát triển cần xử lý dữ liệu ở nhiều định dạng khác nhau và JSON, viết tắt của JavaScript Object Notation, là một trong những định dạng phổ biến nhất được sử dụng trong phát triển web. Đây là cú pháp mà ngôn ngữ JavaScript sử dụng để biểu thị các đối tượng
Là một nhà phát triển Python, bạn có thể nhận thấy rằng điều này trông rất giống với một từ điển Python. Có một số giải pháp khác nhau để làm việc với JSON trong Python và thường thì dữ liệu này được tải vào từ điển
Đối với bài đăng này, chúng tôi sẽ sử dụng dữ liệu JSON đã sửa đổi sau đây từ. Điều hướng đến nơi bạn muốn chạy mã ví dụ, tạo một tệp có tên
import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
4 và thêm phần sau vào đó{
"copyright": "Yin Hao",
"date": "2018-10-30",
"explanation": "Meteors have been shooting out from the constellation of Orion. This was expected, as October is the time of year for the Orionids Meteor Shower. Pictured here, over two dozen meteors were caught in successively added exposures last October over Wulan Hada volcano in Inner Mongolia, China. The featured image shows multiple meteor streaks that can all be connected to a single small region on the sky called the radiant, here visible just above and to the left of the belt of Orion, The Orionids meteors started as sand sized bits expelled from Comet Halley during one of its trips to the inner Solar System. Comet Halley is actually responsible for two known meteor showers, the other known as the Eta Aquarids and visible every May. An Orionids image featured on APOD one year ago today from the same location shows the same car. Next month, the Leonids Meteor Shower from Comet Tempel-Tuttle should also result in some bright meteor streaks. Follow APOD on: Facebook, Instagram, Reddit, or Twitter",
"hdurl": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_2324.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Orionids Meteors over Inner Mongolia",
"url": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_960.jpg"
}
Sử dụng ví dụ này, hãy kiểm tra xem bạn sẽ giải mã và mã hóa dữ liệu này bằng các thư viện Python khác nhau như thế nào
Thư viện tiêu chuẩn
Hãy bắt đầu với sự lựa chọn rõ ràng, mô-đun JSON gốc trong thư viện chuẩn Python. Thư viện này nhận nhiệm vụ mã hóa và giải mã JSON được thực hiện một cách khá dễ sử dụng. Rất nhiều thư viện JSON khác dựa trên API của họ và hoạt động tương tự
Tạo một tệp có tên
import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
5 và dán đoạn mã sau vào tệp đó để giải mã JSON trong tệp văn bản import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
4 của chúng tôi, lưu trữ tệp đó trong từ điển Python, sau đó giải mã lại thành một chuỗiimport json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
Chạy mã của bạn bằng lệnh sau
python test.py
Một trong những ưu điểm của việc sử dụng mô-đun JSON tích hợp là bạn không phải cài đặt bất kỳ thư viện bên thứ ba nào, cho phép bạn có các phụ thuộc tối thiểu
đơn giản
Simplejson là một thư viện JSON đơn giản và nhanh chóng, có chức năng tương tự như mô-đun tích hợp. Một điều thú vị về Simplejson là nó được bảo trì bên ngoài và cập nhật thường xuyên
Bạn sẽ phải cài đặt mô-đun này với pip. Vì vậy, trong thiết bị đầu cuối của bạn, hãy chạy lệnh sau [tốt nhất là trong môi trường ảo]
pip install simplejson==3.16.0
Thư viện này được thiết kế rất giống với mô-đun tích hợp, vì vậy bạn thậm chí không phải thay đổi mã của mình để có được chức năng tương tự. Chỉ cần nhập mô-đun
import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
7, đặt tên cho nó là import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
8 và phần còn lại của mã từ ví dụ trước sẽ hoạt độngThay thế mã trước của bạn bằng mã sau nếu bạn muốn sử dụng Simplejson để mã hóa và giải mã
import simplejson as json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
Một lần nữa, chạy lệnh này bằng lệnh sau
python test.py
Nhiều nhà phát triển Python sẽ đề xuất sử dụng Simplejson thay cho thư viện stock json trong hầu hết các trường hợp vì nó được duy trì tốt
UltraJSON
Giống như Simplejson, ujson là một thư viện JSON khác do cộng đồng duy trì. Tuy nhiên, cái này được viết bằng C và được thiết kế rất nhanh. Nó thiếu một số tính năng nâng cao hơn mà thư viện JSON tích hợp có, nhưng thực sự mang lại lời hứa, vì nó dường như không thể so sánh được về tốc độ
Cài đặt ujson bằng lệnh sau
{
"copyright": "Yin Hao",
"date": "2018-10-30",
"explanation": "Meteors have been shooting out from the constellation of Orion. This was expected, as October is the time of year for the Orionids Meteor Shower. Pictured here, over two dozen meteors were caught in successively added exposures last October over Wulan Hada volcano in Inner Mongolia, China. The featured image shows multiple meteor streaks that can all be connected to a single small region on the sky called the radiant, here visible just above and to the left of the belt of Orion, The Orionids meteors started as sand sized bits expelled from Comet Halley during one of its trips to the inner Solar System. Comet Halley is actually responsible for two known meteor showers, the other known as the Eta Aquarids and visible every May. An Orionids image featured on APOD one year ago today from the same location shows the same car. Next month, the Leonids Meteor Shower from Comet Tempel-Tuttle should also result in some bright meteor streaks. Follow APOD on: Facebook, Instagram, Reddit, or Twitter",
"hdurl": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_2324.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Orionids Meteors over Inner Mongolia",
"url": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_960.jpg"
}
1Như với Simplejson, bạn không phải thay đổi bất kỳ mã nào để nó hoạt động. Trong hầu hết các trường hợp, theo quan điểm của nhà phát triển, nó hoạt động giống như mô-đun tích hợp sẵn. Thay thế mã trước đó của bạn bằng mã sau
{
"copyright": "Yin Hao",
"date": "2018-10-30",
"explanation": "Meteors have been shooting out from the constellation of Orion. This was expected, as October is the time of year for the Orionids Meteor Shower. Pictured here, over two dozen meteors were caught in successively added exposures last October over Wulan Hada volcano in Inner Mongolia, China. The featured image shows multiple meteor streaks that can all be connected to a single small region on the sky called the radiant, here visible just above and to the left of the belt of Orion, The Orionids meteors started as sand sized bits expelled from Comet Halley during one of its trips to the inner Solar System. Comet Halley is actually responsible for two known meteor showers, the other known as the Eta Aquarids and visible every May. An Orionids image featured on APOD one year ago today from the same location shows the same car. Next month, the Leonids Meteor Shower from Comet Tempel-Tuttle should also result in some bright meteor streaks. Follow APOD on: Facebook, Instagram, Reddit, or Twitter",
"hdurl": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_2324.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Orionids Meteors over Inner Mongolia",
"url": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_960.jpg"
}
2Chạy cái này với lệnh sau
python test.py
Nếu bạn đang xử lý các bộ dữ liệu thực sự lớn và tuần tự hóa JSON đang trở thành một nhiệm vụ tốn kém, thì ujson là một thư viện tuyệt vời để sử dụng
Thư viện yêu cầu
Các thư viện tuần tự hóa JSON này rất tuyệt, nhưng trong thế giới thực thường có nhiều ngữ cảnh hơn xung quanh lý do tại sao bạn phải xử lý dữ liệu JSON. Một trong những tình huống phổ biến nhất yêu cầu giải mã JSON là khi thực hiện các yêu cầu HTTP tới API REST của bên thứ ba
Thư viện yêu cầu là công cụ Python phổ biến nhất để thực hiện các yêu cầu HTTP và nó có một phương thức
import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
9 tích hợp khá tuyệt vời trên đối tượng phản hồi được trả về khi yêu cầu HTTP của bạn kết thúc. Thật tuyệt khi có một giải pháp tích hợp để bạn không phải nhập thêm thư viện cho một tác vụ đơn giảnCài đặt các yêu cầu bằng lệnh shell sau
{
"copyright": "Yin Hao",
"date": "2018-10-30",
"explanation": "Meteors have been shooting out from the constellation of Orion. This was expected, as October is the time of year for the Orionids Meteor Shower. Pictured here, over two dozen meteors were caught in successively added exposures last October over Wulan Hada volcano in Inner Mongolia, China. The featured image shows multiple meteor streaks that can all be connected to a single small region on the sky called the radiant, here visible just above and to the left of the belt of Orion, The Orionids meteors started as sand sized bits expelled from Comet Halley during one of its trips to the inner Solar System. Comet Halley is actually responsible for two known meteor showers, the other known as the Eta Aquarids and visible every May. An Orionids image featured on APOD one year ago today from the same location shows the same car. Next month, the Leonids Meteor Shower from Comet Tempel-Tuttle should also result in some bright meteor streaks. Follow APOD on: Facebook, Instagram, Reddit, or Twitter",
"hdurl": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_2324.jpg",
"media_type": "image",
"service_version": "v1",
"title": "Orionids Meteors over Inner Mongolia",
"url": "//apod.nasa.gov/apod/image/1810/Orionids_Hao_960.jpg"
}
5Trong ví dụ này, chúng tôi thực sự sẽ thực hiện một yêu cầu HTTP tới API Hình ảnh thiên văn trong ngày thay vì sử dụng tệp
python test.py
0 được mã hóa cứng cục bộ từ các ví dụ khácMở một tệp mới có tên là
python test.py
1 và thêm đoạn mã sau vào đóimport json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
0Mã này tạo một yêu cầu HTTP
python test.py
2 tới API của NASA, phân tích cú pháp dữ liệu JSON mà nó trả về bằng phương thức tích hợp sẵn này và in ra lời giải thích về Bức tranh thiên văn trong ngày hiện tạiChạy mã của bạn bằng lệnh sau
import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
1Trả lời yêu cầu HTTP bằng JSON trong Flask
Một tình huống phổ biến khác là bạn đang xây dựng tuyến đường trên ứng dụng web và muốn phản hồi các yêu cầu bằng dữ liệu JSON. Flask, một khung web nhẹ phổ biến dành cho Python, có chức năng tích hợp sẵn để xử lý tuần tự hóa dữ liệu của bạn cho bạn
Cài đặt Flask với pip
import json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
2Và bây giờ hãy tạo một tệp mới có tên là
python test.py
3, nơi chứa mã cho ứng dụng web mẫu của chúng taimport json
with open['apod.json', 'r'] as f:
json_text = f.read[]
# Decode the JSON string into a Python dictionary.
apod_dict = json.loads[json_text]
print[apod_dict['explanation']]
# Encode the Python dictionary into a JSON string.
new_json_string = json.dumps[apod_dict, indent=4]
print[new_json_string]
3Trong mã này, chúng tôi có một tuyến đường có tên là
python test.py
4 và bất cứ khi nào một yêu cầu python test.py
2 được gửi đến tuyến đường đó, hàm python test.py
6 được gọi. Trong chức năng này, chúng tôi đang giả vờ trả lời bằng Hình ảnh thiên văn trong ngày. Trong ví dụ này, dữ liệu chúng tôi trả về chỉ được mã hóa cứng, nhưng bạn có thể thay thế dữ liệu này bằng dữ liệu từ bất kỳ nguồn nào khácChạy tệp với
python test.py
7, sau đó truy cập http. //máy chủ cục bộ. 5000/apod trong trình duyệt của bạn để xem dữ liệu JSONTheo tài liệu Flask, hàm
python test.py
8 lấy dữ liệu ở dạng- đối số duy nhất. Chuyển thẳng qua
- Nhiều đối số. Chuyển đổi thành một mảng trước khi được chuyển đến
- Nhiều đối số từ khóa. Chuyển đổi thành một dict trước khi được chuyển đến
- Cả args và kwargs. Hành vi không xác định và sẽ đưa ra một ngoại lệ
Chức năng này kết thúc để thêm một vài cải tiến giúp cuộc sống dễ dàng hơn. Nó biến đầu ra JSON thành một đối tượng với mô phỏng ứng dụng/json
Phần kết luận
Có nhiều giải pháp khác nhau để làm việc với JSON trong Python và tôi đã chỉ cho bạn một số ví dụ trong bài đăng này. Bạn có thể sử dụng bất kỳ thư viện nào phù hợp với nhu cầu cá nhân của mình hoặc trong trường hợp yêu cầu và Flask, thậm chí có thể không phải nhập một thư viện JSON cụ thể