Python JSON: Enkoding, Dekoding, dan Penanganan File – Panduan Praktis
Apa Itu JSON dalam Python?
JSON—singkatan dari JavaScript Object Notation—adalah format pertukaran data berbasis teks yang paling banyak digunakan. Dalam Python ia memetakan secara langsung ke struktur data native: objek menjadi dict, array menjadi list, string, angka, boolean, dan null menerjemahkan ke str, int/float, bool, dan None masing-masing. Modul json dalam perpustakaan standar menangani semua konversi.
Pustaka JSON dalam Python
Impor modul sekali dalam skrip Anda:
import json
Modul menawarkan empat metode inti:
| Metode | Deskripsi |
|---|
| dumps() | Mengonversi objek Python menjadi string JSON. |
| dump() | Menulis string JSON langsung ke objek file. |
| loads() | Mengurai string JSON menjadi objek Python. |
| load() | Membaca dan mengurai file JSON menjadi objek Python. |
Python ke JSON (Enkoding)
Enkoding adalah proses mengonversi tipe data Python menjadi JSON. Pemetaan default ditunjukkan di bawah ini:
| Python | JSON |
|---|
| dict | Objek |
| list | Array |
| str/unicode | String |
| int/long | Angka (int) |
| float | Angka (real) |
| True | true |
| False | false |
| None | null |
Contoh menggunakan json.dumps():
import json x = { "name": "Ken", "age": 45, "married": True, "children": ("Alice", "Bob"), "pets": ["Dog"], "cars": [ {"model": "Audi A1", "mpg": 15.1}, {"model": "Zeep Compass", "mpg": 18.1} ] } # Pretty-print dengan kunci yang diurutkan sorted_string = json.dumps(x, indent=4, sort_keys=True) print(sorted_string) Output:
{ "age": 45, "cars": [ { "model": "Audi A1", "mpg": 15.1 }, { "model": "Zeep Compass", "mpg": 18.1 } ], "children": [ "Alice", "Bob" ], "married": true, "name": "Ken", "pets": [ "Dog" ] } Menulis objek JSON ke file adalah mudah dengan json.dump():
with open('json_file.json', 'w') as file_write: json.dump(x, file_write, indent=4, sort_keys=True) Setelah menjalankan skrip, json_file.json akan berisi data yang terserialisasi.
JSON ke Python (Dekoding)
Dekoding membalik pemetaan, mengubah string atau file JSON kembali menjadi objek Python native. Tabel konversi mencermini tabel enkoding:
| JSON | Python |
|---|
| Objek | dict |
| Array | list |
| String | str |
| Angka (int) | int |
| Angka (real) | float |
| true | True |
| false | False |
| null | None |
Contoh menggunakan json.loads():
import json person_data = '{"person": {"name": "Kenn", "sex": "male", "age": 28}}' obj = json.loads(person_data) print(obj) print(type(obj)) print(obj.get('person')) Output:
{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}} <class 'dict'> {'name': 'Kenn', 'sex': 'male', 'age': 28} Membaca file JSON secara langsung:
with open('json_file.json') as f: data = json.load(f) print(data) Output:
{'name': 'Ken', 'age': 45, ...} Enkoding Kompak dan Pretty-Print
Untuk transmisi jaringan, enkoding kompak menghapus spasi putih:
lst = ['a', 'b', 'c', {"4": 5, "6": 7}] compact = json.dumps(lst, separators=(',', ':')) print(compact) Output:
["a","b","c",{"4":5,"6":7}] Untuk keterbacaan manusia, pretty-printing menggunakan indentasi:
dic = {"a": 4, "b": 5} pretty = json.dumps(dic, indent=4, separators=(',', ': ')) print(pretty) Output:
{ "a": 4, "b": 5 } Enkoding Objek Kompleks
Modul json tidak dapat menserialisasi objek sembarang. Untuk menangani bilangan complex, berikan fungsi default:
def complex_encode(o): if isinstance(o, complex): return [o.real, o.imag] raise TypeError(f"{repr(o)} is not JSON serializable") print(json.dumps(4 + 5j, default=complex_encode)) Output:
[4.0, 5.0]
Dekoding Objek Kompleks
Gunakan object_hook untuk mendeteksi marker khusus dan membangun kembali bilangan kompleks:
def is_complex(obj): if "__complex__" in obj: return complex(obj["real"], obj["img"]) return obj complex_obj = json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook=is_complex) print(complex_obj) Output:
(4+5j)
Kelas Serialisasi & Deserialisasi
Kelas JSONEncoder dan JSONDecoder menyediakan kontrol yang lebih halus:
JSONEncoder.default(o) – imbalhasil untuk menserialisasi objek kustom. JSONEncoder.encode(o) – mengembalikan string JSON. JSONEncoder.iterencode(o) – iterasi atas output string. JSONDecoder.decode(s) – mengurai string JSON. JSONDecoder.raw_decode(s) – mengurai mulai dari indeks yang diberikan.
Contoh:
from json.encoder import JSONEncoder print(JSONEncoder().encode({"colour": ["red", "yellow", "green"]})) Mengambil JSON dari URL
Menggunakan requests untuk mengunduh umpan JSON langsung (misalnya, CityBike NYC):
import json, requests response = requests.get("https://feeds.citibikenyc.com/stations/stations.json") bike_dict = json.loads(response.text) print(bike_dict['stationBeanList'][0]) Output:
{ 'id': 487, 'stationName': 'E 20 St & FDR Drive', 'availableDocks': 24, ... } Menangani Pengecualian JSON
Pengecualian utama adalah json.JSONDecodeError, subclass dari ValueError. Contoh penanganan:
try: with open('bad.json') as f: data = json.load(f) except json.JSONDecodeError as e: print(f"JSON buruk: {e}") Nilai Numerik Khusus
RFC 8259 tidak mengizinkan Infinity atau NaN, tetapi encoder Python mewakilinya sebagai string:
print(json.dumps(float('inf'))) print(json.dumps(float('nan'))) Output:
Infinity NaN
Kunci Berulang dalam JSON
Saat kunci muncul beberapa kali, json.loads() Python hanya mempertahankan kemunculan terakhir:
json.loads('{"a": 1, "a": 2, "a": 3}') # -> {'a': 3} Alat Baris Perintah
Modul json.tool memformat dan memvalidasi JSON dari baris perintah:
$ echo '{"name": "Kings Arthur"}' | python3 -m json.tool { "name": "Kings Arthur" } Keuntungan JSON dalam Python
- Dukungan native melalui modul
json. - Dapat dibaca manusia dengan pretty-printing.
- Diterima luas untuk API, konfigurasi, dan penyimpanan data.
- Agnostik bahasa dan ringan.
Keterbatasan
- Tidak mendukung tipe data kustom tanpa enkoder kustom.
- Batas rekursi maksimum membatasi struktur yang bersarang dalam.
- Dokumen besar dapat memakan banyak memori untuk dimuat sepenuhnya.
Cheat Sheet JSON Python
| Fungsi | Deskripsi |
|---|
| json.dumps(obj) | Serialisasi objek Python ke string JSON. |
| json.dump(obj, file) | Tulis string JSON ke file. |
| json.dumps(obj, separators=(",", ":")) | Representasi kompak tanpa spasi. |
| json.dumps(obj, indent=4) | JSON pretty-printed dengan indentasi. |
| json.dumps(obj, sort_keys=True) | Urutkan kunci dictionary secara alfabetis. |
| json.dumps(obj, default=custom) | Encode objek yang tidak didukung. |
| JSONEncoder().encode(obj) | Serialisasi manual melalui kelas encoder. |
| json.loads(s) | Urai string JSON ke objek Python. |
| json.loads(s, object_hook=custom) | Logika deserialisasi kustom. |
| JSONDecoder().decode(s) | Deserialisasi manual melalui kelas decoder. |