,

Manipulasi File JSON di Python

rantissi Avatar
Manipulasi File JSON di Python

Apa itu JSON?

JSON (JavaScript Object Notation) = format penyimpanan data yang ringan & mudah dibaca.

Mirip dictionary Python:

{
  "nama": "Ran",
  "umur": 20,
  "hobi": ["ngoding", "makan", "tidur"]
}

Konversi JSON <=> Python

import json

# Python -> JSON
data = {"nama": "Ran", "umur": 20}
with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

# JSON -> Python
with open("data.json", "r") as file:
    hasil = json.load(file)
    print(hasil["nama"])

Contoh Data List of Dictionary:

mahasiswa = [
    {"nama": "Ran", "nim": "123", "prodi": "Informatika"},
    {"nama": "Ali", "nim": "124", "prodi": "Sistem Informasi"}
]

# Simpan ke JSON
with open("mahasiswa.json", "w") as file:
    json.dump(mahasiswa, file, indent=4)

# Baca lagi dan tampilkan
with open("mahasiswa.json", "r") as file:
    daftar = json.load(file)
    for m in daftar:
        print(m["nama"], "-", m["prodi"])

Leave a Reply

Your email address will not be published. Required fields are marked *