Menu
CoddyTech

Mendekode JSON Kustom

Pelajaran 9 dari 9 dalam kursus Python JSON di Coddy.

Penguraian JSON kustom adalah fitur lanjutan dari module json Python yang memungkinkan kamu mengatur cara data JSON dikonversi 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 dapat menggunakannya dengan json.loads() atau json.load():


decoded_object = json.loads(json_string, cls=CustomDecoder)

Contoh: Mengurai Menjadi Object Kustom

Mari lihat contoh praktis saat kita mengurai 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 Penting

  • Method object_hook dipanggil untuk setiap object yang diurai.
  • Kamu dapat memeriksa kata kunci atau pola tertentu untuk menentukan cara mengurai object.
  • 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 dapat mengintegrasikan data JSON ke dalam model object aplikasi Python-mu dengan lancar, sehingga deserialisasi data menjadi lebih fleksibel dan sesuai dengan kebutuhan spesifikmu.

quiz iconUji dirimu

Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.

quiz iconUji dirimu

Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.

quiz iconUji dirimu

Pelajaran ini berisi kuis singkat. Mulai pelajarannya untuk menjawab kuis dan melacak progresmu.

challenge icon

Tantangan

Mudah

Buat decoder JSON khusus untuk sistem data cuaca. Decoder ini harus mengonversi string JSON menjadi object WeatherData dengan atribut dan konversi tertentu. Terapkan hal berikut:

  1. Definisikan class WeatherData dengan atribut: location, temperature, humidity, dan conditions.
  2. Buat subclass khusus dari JSONDecoder yang:
    • 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.
  3. 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 Python JSON

Latihan sendiri: Compiler Python online