JSON (JavaScript Object Notation) is the universal language of web APIs. Understanding how to work with JSON efficiently can save you hours every week.
JSON Syntax
{
"name": "John Doe",
"age": 30,
"isActive": true,
"score": 9.5,
"tags": ["developer", "kotlin", "android"],
"address": {
"city": "Dhaka",
"country": "Bangladesh"
},
"phone": null
}
JSON Data Types
- String โ "hello" (always double quotes)
- Number โ 42, 3.14, -1 (no quotes)
- Boolean โ true, false (lowercase)
- Null โ null (lowercase)
- Array โ [1, 2, 3] or ["a", "b"]
- Object โ {"key": "value"}
Parsing JSON in Different Languages
// Kotlin with Gson
data class User(
val name: String,
val age: Int,
val email: String
)
val gson = Gson()
// Parse JSON string to object
val user = gson.fromJson(jsonString, User::class.java)
// Convert object to JSON string
val json = gson.toJson(user)
// Kotlin Serialization (modern approach)
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class User(val name: String, val age: Int)
val user = Json.decodeFromString(jsonString)
val json = Json.encodeToString(user)
// JavaScript
const json = JSON.stringify({ name: "John", age: 30 });
// โ {"name":"John","age":30}
const obj = JSON.parse(json);
// โ { name: "John", age: 30 }
// Pretty print
JSON.stringify(obj, null, 2);
// Formatted with 2-space indent
Common JSON Errors
// โ Trailing comma - INVALID
{"name": "John", "age": 30,}
// โ Single quotes - INVALID
{name: John}
// โ Comments - INVALID (use JSON5 or JSONC for comments)
{
// This is a comment - NOT valid JSON
"name": "John"
}
// โ Valid JSON
{"name": "John", "age": 30}
Working with Nested JSON
// Access nested values safely
val json = """
{
"user": {
"profile": {
"avatar": "https://example.com/avatar.jpg"
}
}
}
"""
val element = JsonParser.parseString(json).asJsonObject
val avatar = element
?.getAsJsonObject("user")
?.getAsJsonObject("profile")
?.get("avatar")
?.asString
// With Kotlin Serialization
@Serializable
data class ApiResponse(
val user: UserData,
val status: String,
val timestamp: Long
)
@Serializable
data class UserData(
val profile: Profile,
val settings: Settings? = null // optional field
)
๐ Format & Validate JSON
Format messy JSON, validate syntax, sort keys and minify with our professional JSON Formatter tool.
Open JSON Formatter โ