JSON Array vs Object: Kapan Pakai Yang Mana?
Pertanyaan yang kelihatannya sepele tapi sering bikin developer pemula bingung: kapan sebaiknya data direpresentasikan sebagai array [...], dan kapan sebagai object {...}? Keduanya sama-sama bisa "menampung banyak item", tapi punya semantik dan implikasi teknis yang cukup berbeda. Pilihan yang salah bisa bikin API sulit dipakai, rawan bug, atau sulit di-extend di masa depan.
Perbedaan Mendasar
Array adalah koleksi terurut (ordered) yang diakses berdasarkan posisi/index. Object adalah koleksi key-value yang diakses berdasarkan nama key, dan secara semantik dianggap tidak terurut (meskipun dalam praktiknya banyak parser modern mempertahankan urutan insersi, ini bukan jaminan yang bisa diandalkan across semua implementasi). Perbedaan konseptual ini bukan sekadar detail teknis — ia langsung mempengaruhi bagaimana consumer API menulis kode untuk mengakses data tersebut, dan seberapa mudah struktur itu berevolusi di masa depan tanpa merusak client yang sudah ada.
// Array — akses via index
["apple", "banana", "cherry"][0] // "apple"
// Object — akses via key
{"first": "apple", "second": "banana"}["first"] // "apple"
Kapan Pakai Array
Gunakan array ketika:
- Urutan itu penting — misalnya daftar langkah instruksi, riwayat transaksi terurut waktu, atau ranking leaderboard.
- Item-item bersifat homogen — semua elemen punya bentuk/struktur yang sama, seperti daftar produk atau daftar user.
- Jumlah item bisa berubah-ubah secara dinamis dan kamu perlu operasi seperti append, filter, atau iterasi berurutan.
- Kamu tidak butuh akses cepat berdasarkan identifier unik — kalau akses utama cuma "ambil semua" atau "loop semua", array sudah cukup.
{
"products": [
{ "id": 1, "name": "Kaos Polos" },
{ "id": 2, "name": "Celana Jeans" }
]
}
Kapan Pakai Object
Gunakan object ketika:
- Kamu butuh akses cepat (O(1) lookup) berdasarkan key unik — misalnya mengambil data user berdasarkan ID tanpa perlu loop mencari.
- Setiap item punya identitas yang jelas dan unik yang cocok dijadikan key, seperti kode negara, slug, atau ID.
- Struktur mewakili "record" dengan field yang punya makna berbeda-beda (bukan koleksi item sejenis) — misalnya data satu user dengan field
name,email,age. - Urutan tidak relevan secara semantik — kalau urutan data tidak mempengaruhi arti data itu, object lebih tepat secara konseptual.
{
"usersById": {
"u001": { "name": "Sarah Amelia" },
"u002": { "name": "Budi Santoso" }
}
}
Dibandingkan representasi array untuk kasus yang sama:
{
"users": [
{ "id": "u001", "name": "Sarah Amelia" },
{ "id": "u002", "name": "Budi Santoso" }
]
}
Kedua bentuk ini valid, tapi dengan trade-off berbeda: bentuk object memudahkan lookup langsung (usersById["u001"]), sementara bentuk array lebih mudah untuk iterasi berurutan, sorting, atau ditampilkan sebagai list/tabel di UI. Tim frontend biasanya lebih menyukai bentuk array karena lebih mudah di-loop dengan map()/filter(), sementara tim yang membangun cache atau state management di sisi client kadang lebih suka bentuk object supaya update satu item tidak perlu mencari index-nya lebih dulu.
Kesalahan Umum: Memakai Object Padahal Harusnya Array
Kesalahan desain yang cukup sering terjadi adalah memakai object dengan key berupa angka berurutan, padahal maksudnya adalah list:
// Kurang tepat
{
"0": "apple",
"1": "banana",
"2": "cherry"
}
// Lebih tepat
["apple", "banana", "cherry"]
Pola pertama sering muncul secara tidak sengaja akibat serialisasi otomatis dari bahasa pemrograman tertentu (misalnya PHP associative array yang keynya kebetulan angka berurutan). Ini bikin bingung konsumen API — mereka harus menebak apakah itu "object beneran" atau "array yang salah bentuk". Kalau kamu menemukan pola ini di API yang sedang kamu desain, hampir selalu lebih baik memperbaikinya menjadi array asli sebelum dipublikasikan, karena mengubahnya belakangan setelah banyak client bergantung padanya jauh lebih menyakitkan.
Kesalahan Umum: Memakai Array Padahal Harusnya Object
Sebaliknya, kadang orang memakai array untuk data yang sebenarnya lebih cocok jadi object, misalnya representasi field dengan nama tetap:
// Kurang tepat — urutan implisit yang mudah salah
["Sarah Amelia", "sarah@example.com", 29]
// Lebih tepat — jelas field mana yang mana
{ "name": "Sarah Amelia", "email": "sarah@example.com", "age": 29 }
Representasi array untuk record dengan field bermakna berbeda sangat rawan bug — kalau urutan field berubah di versi API berikutnya (misalnya ditambah satu field di tengah), semua client yang mengandalkan index posisi akan rusak diam-diam tanpa error yang jelas.
Kasus Ambigu: Kapan Boleh Keduanya?
Beberapa API menyediakan dua representasi untuk kebutuhan berbeda, misalnya endpoint utama mengembalikan array untuk ditampilkan berurutan, sementara endpoint atau field terpisah menyediakan bentuk object untuk lookup cepat. Ini valid selama didokumentasikan dengan jelas dan tidak membingungkan konsumen API tentang representasi mana yang jadi "sumber kebenaran".
Pertimbangan Performa
Dari sisi performa runtime, lookup di object (biasanya diimplementasikan sebagai hash map di kebanyakan bahasa pemrograman) jauh lebih cepat — O(1) rata-rata — dibanding mencari item tertentu di array yang butuh O(n) karena harus di-loop satu-satu (kecuali di-sort dan pakai binary search). Kalau kamu tahu use case utamanya adalah "cari item spesifik berdasarkan ID dengan cepat", dan datasetnya besar, representasi object bisa memberi keuntungan performa nyata di sisi client setelah data di-parse.
Bagaimana Bahasa Pemrograman Memetakan Ini?
Perlu diingat, "array" dan "object" di JSON adalah konsep abstrak yang dipetakan berbeda-beda tergantung bahasa pemrograman yang men-decode-nya. Di JavaScript, array JSON jadi Array dan object JSON jadi Object biasa — sangat natural karena JSON memang meniru sintaks JS. Di Python, array jadi list dan object jadi dict. Di Java atau Go yang statically typed, biasanya kamu perlu mendefinisikan struct/class eksplisit terlebih dahulu supaya proses decode tahu field apa saja yang diharapkan — array JSON dipetakan ke List/slice, dan object ke instance class. Perbedaan ini kadang membuat desain "array vs object" yang terlihat sepele di JSON ternyata berdampak signifikan ke kompleksitas kode consumer di bahasa yang lebih strict soal tipe.
Rangkuman Cepat
- Urutan penting, item homogen, butuh iterasi → array
- Butuh lookup cepat by key, item punya identitas unik → object
- Record dengan field bermakna berbeda-beda → object, bukan array posisional
- List sederhana tanpa makna khusus di posisinya → array, bukan object dengan key angka
JSON Array vs Object: When to Use Which?
A question that looks trivial but often trips up beginner developers: when should data be represented as an array [...], and when as an object {...}? Both can "hold multiple items," but they carry quite different semantics and technical implications. Picking the wrong one can make an API hard to use, bug-prone, or hard to extend later.
The Fundamental Difference
An array is an ordered collection accessed by position/index. An object is a key-value collection accessed by key name, and is semantically considered unordered (though in practice many modern parsers preserve insertion order, this isn't a reliable guarantee across every implementation).
// Array — access via index
["apple", "banana", "cherry"][0] // "apple"
// Object — access via key
{"first": "apple", "second": "banana"}["first"] // "apple"
When to Use an Array
Use an array when:
- Order matters — e.g. a list of instruction steps, a chronologically-ordered transaction history, or a leaderboard ranking.
- Items are homogeneous — every element has the same shape/structure, like a product list or a user list.
- The number of items changes dynamically and you need operations like appending, filtering, or sequential iteration.
- You don't need fast lookup by a unique identifier — if the main access pattern is "get all" or "loop through all," an array is sufficient.
{
"products": [
{ "id": 1, "name": "Plain T-Shirt" },
{ "id": 2, "name": "Jeans" }
]
}
When to Use an Object
Use an object when:
- You need fast (O(1)) lookup by a unique key — e.g. fetching user data by ID without needing to loop and search.
- Each item has a clear, unique identity that's suitable as a key, like a country code, slug, or ID.
- The structure represents a "record" whose fields carry different meanings (rather than a collection of like items) — e.g. a single user's data with
name,email,agefields. - Order isn't semantically relevant — if the ordering of the data doesn't affect its meaning, an object is conceptually more appropriate.
{
"usersById": {
"u001": { "name": "Sarah Amelia" },
"u002": { "name": "Budi Santoso" }
}
}
Compare that to an array representation of the same case:
{
"users": [
{ "id": "u001", "name": "Sarah Amelia" },
{ "id": "u002", "name": "Budi Santoso" }
]
}
Both forms are valid, but with different trade-offs: the object form makes direct lookup easy (usersById["u001"]), while the array form is easier for sequential iteration, sorting, or rendering as a list/table in a UI.
Common Mistake: Using an Object When It Should Be an Array
A fairly common design mistake is using an object with sequential numeric keys, when what's really meant is a list:
// Not ideal
{
"0": "apple",
"1": "banana",
"2": "cherry"
}
// Better
["apple", "banana", "cherry"]
This pattern often shows up unintentionally due to automatic serialization from certain programming languages (e.g. a PHP associative array whose keys happen to be sequential numbers). It confuses API consumers — they have to guess whether it's a "real object" or a "malformed array."
Common Mistake: Using an Array When It Should Be an Object
Conversely, sometimes people use an array for data that's really better suited to an object, like representing fields with fixed meanings:
// Not ideal — implicit order that's easy to get wrong
["Sarah Amelia", "sarah@example.com", 29]
// Better — clear which field is which
{ "name": "Sarah Amelia", "email": "sarah@example.com", "age": 29 }
Array representation for a record with distinctly-meaningful fields is very bug-prone — if the field order changes in a later API version (e.g. a new field is inserted in the middle), every client relying on positional index will silently break with no clear error.
An Ambiguous Case: When Is It Fine to Have Both?
Some APIs provide two representations for different needs — e.g. a main endpoint returns an array for ordered display, while a separate endpoint or field provides an object form for fast lookup. This is fine as long as it's clearly documented and doesn't confuse API consumers about which representation is the "source of truth."
Performance Considerations
From a runtime performance standpoint, object lookup (typically implemented as a hash map in most programming languages) is much faster — O(1) on average — compared to searching for a specific item in an array, which needs O(n) since it has to be looped through one by one (unless sorted and searched with binary search). If you know the main use case is "quickly find a specific item by ID" and the dataset is large, an object representation can give a real performance win on the client side after parsing.
How Do Programming Languages Map This?
Keep in mind that "array" and "object" in JSON are abstract concepts that get mapped differently depending on the language decoding them. In JavaScript, a JSON array becomes an Array and a JSON object becomes a plain Object — very natural since JSON's syntax mirrors JS. In Python, an array becomes a list and an object becomes a dict. In statically-typed languages like Java or Go, you usually need to define an explicit struct/class beforehand so the decoding process knows which fields to expect — a JSON array maps to a List/slice, and an object to a class instance. This difference sometimes means a design choice between "array vs object" that looks trivial in JSON actually has a significant impact on consumer code complexity in a language stricter about types.
Quick Summary
- Order matters, items are homogeneous, need iteration → array
- Need fast lookup by key, items have unique identity → object
- A record with distinctly-meaningful fields → object, not a positional array
- A simple list with no special meaning to position → array, not an object with numeric keys