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

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 โ†’