Dekoding JSON Kustom
Pelajaran 9 dari 9 dalam kursus JSON Python di Coddy.
Penguraian JSON kustom adalah fitur lanjutan dari module json Python yang memungkinkan kamu mengontrol cara data JSON diubah menjadi object Python. Fitur ini sangat berguna saat menangani struktur data yang kompleks atau saat kamu ingin membuat object Python tertentu dari data JSON.
Class JSONDecoder
Untuk menerapkan penguraian JSON kustom, kamu perlu membuat subclass dari class json.JSONDecoder dan mengganti method object_hook:
import json
class CustomDecoder(json.JSONDecoder):
def object_hook(self, dct):
# Logika decoding khusus di sini
return dct
Menggunakan Decoder Kustom
Setelah mendefinisikan decoder kustom, kamu bisa menggunakannya dengan json.loads() atau json.load():
decoded_object = json.loads(json_string, cls=CustomDecoder)
Contoh: Mengurai Menjadi Object Kustom
Mari lihat contoh praktis penguraian data JSON menjadi object Python kustom:
import json
from datetime import datetime
class Person:
def __init__(self, name, birthdate):
self.name = name
self.birthdate = birthdate
class CustomDecoder(json.JSONDecoder):
def object_hook(self, dct):
if 'name' in dct and 'birthdate' in dct:
return Person(dct['name'], datetime.fromisoformat(dct['birthdate']))
return dct
json_string = '{"name": "Alice", "birthdate": "1990-05-15"}'
person = json.loads(json_string, cls=CustomDecoder)
print(type(person)) # output: <class '__main__.Person'>
print(person.name) # output: Alice
print(person.birthdate) # output: 1990-05-15 00:00:00
Poin Utama
- Method
object_hookdipanggil untuk setiap object yang diurai. - Kamu bisa memeriksa kata kunci atau pola tertentu untuk menentukan cara mengurai object tersebut.
- Kembalikan object apa adanya jika struktur tersebut tidak memerlukan penguraian kustom.
- Decoder kustom berguna untuk membuat object khusus domain secara langsung dari data JSON.
Dengan menggunakan decoder JSON kustom, kamu bisa mengintegrasikan data JSON dengan lancar ke dalam model object aplikasi Python-mu, sehingga deserialisasi data menjadi lebih fleksibel dan sesuai dengan kebutuhan spesifikmu.
Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.
Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.
Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.
Tantangan
MudahBuat decoder JSON khusus untuk sistem data cuaca. Decoder ini harus mengonversi string JSON menjadi object WeatherData dengan atribut dan konversi tertentu. Terapkan hal berikut:
- Definisikan class
WeatherDatadengan atribut:location,temperature,humidity, danconditions. - Buat subclass khusus dari
JSONDecoderyang:- Mengonversi suhu dari Fahrenheit ke Celsius, dibulatkan hingga satu angka desimal.
- Memastikan kelembapan dinyatakan sebagai persentase (misalnya, 0.65 menjadi 65%).
- Menggunakan huruf kapital pada setiap kata dalam string kondisi.
- Terapkan fungsi yang menerima string JSON, menggunakan decoder khusus untuk menguraikannya, lalu mengembalikan string berformat dengan data cuaca.
Input berikut akan diberikan:
{"location": "new york", "temperature": 72, "humidity": 0.65, "conditions": "partly cloudy"}
Cetak string hasil dengan format berikut:
"Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"
Coba sendiri
Here's a suitable starter code for the challenge:
```python
import json
# Read input
json_string = input()
class WeatherData:
def __init__(self, location, temperature, humidity, conditions):
self.location = location
self.temperature = temperature
self.humidity = humidity
self.conditions = conditions
class CustomJSONDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, dct):
# TODO: Implement the custom decoding logic here
pass
def parse_weather_data(json_string):
# TODO: Implement the parsing function here
pass
# TODO: Use the CustomJSONDecoder and parse_weather_data function to process the input
# Placeholder for the result
result = "Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"
# Output the result
print(result)
```Semua pelajaran di JSON Python
Latihan sendiri: Compiler Python online