JSON Basics: Understanding Key-Value Pairs

JSON Basics: Understanding Key-Value Pairs

A JSON object is a collection of key-value pairs:

{
    "name": "Alice",
    "age": 30,
    "active": true
}

Keys are strings. Values can be strings, numbers, booleans, arrays, objects, or null.

Basic Syntax Rules

Keys must be strings in double quotes:

// Valid
{ "name": "Alice" }

// Invalid - single quotes not allowed
{ 'name': 'Alice' }

// Invalid - unquoted keys
{ name: "Alice" }

Strings use double quotes:

{ "message": "Hello, world!" }

Single quotes aren't valid JSON.

No trailing commas:

// Valid
{ "a": 1, "b": 2 }

// Invalid - trailing comma
{ "a": 1, "b": 2, }

Value Types

String:

{ "name": "Alice" }

Number:

{ "age": 30, "price": 19.99, "count": -5 }

Numbers can be integers or floats, positive or negative.

Boolean:

{ "active": true, "verified": false }

Null:

{ "middleName": null }

Array:

{ "tags": ["json", "data", "format"] }

Object (nested):

{
    "user": {
        "name": "Alice",
        "email": "alice@example.com"
    }
}

Accessing Values

In JavaScript:

const data = {
    "name": "Alice",
    "age": 30
};

console.log(data.name);      // "Alice"
console.log(data["age"]);    // 30

Dot notation or bracket notation work.

Key Naming Conventions

camelCase (most common):

{
    "firstName": "Alice",
    "lastName": "Smith",
    "emailAddress": "alice@example.com"
}

snake_case:

{
    "first_name": "Alice",
    "last_name": "Smith",
    "email_address": "alice@example.com"
}

kebab-case (requires bracket notation in JavaScript):

{
    "first-name": "Alice"
}

// Must use brackets
data["first-name"]  // Can't use data.first-name

Stick to camelCase or snake_case for consistency.

Special Characters in Keys

Keys can contain spaces and special characters if quoted:

{
    "full name": "Alice Smith",
    "email@address": "alice@example.com",
    "price ($)": 29.99
}

But avoid this. Simple alphanumeric keys are clearer.

Reserved Words

JSON has no reserved words. These are all valid:

{
    "class": "Math",
    "function": "calculate",
    "return": true
}

Though they might cause issues when converted to JavaScript objects.

Parsing JSON

Convert JSON string to JavaScript object:

const jsonString = '{"name": "Alice", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name);  // "Alice"

Convert JavaScript object to JSON string:

const obj = { name: "Alice", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString);  // '{"name":"Alice","age":30}'

Pretty Printing

Readable JSON with indentation:

const obj = { name: "Alice", age: 30 };
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
// {
//   "name": "Alice",
//   "age": 30
// }

The 2 specifies 2 spaces for indentation.

Nested Objects

{
    "user": {
        "id": 123,
        "profile": {
            "name": "Alice",
            "location": {
                "city": "New York",
                "country": "USA"
            }
        }
    }
}

Access nested values:

data.user.profile.location.city  // "New York"

Multiple Key-Value Pairs

{
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com",
    "age": 30,
    "active": true,
    "roles": ["admin", "user"],
    "metadata": {
        "lastLogin": "2024-01-15",
        "loginCount": 42
    }
}

Order of Keys

JSON objects are unordered collections. Key order isn't guaranteed:

{ "a": 1, "b": 2 }
// Might be parsed as
{ "b": 2, "a": 1 }

Don't rely on key order. Use arrays for ordered data.

Common Mistakes

Trailing commas:

// Invalid
{ "name": "Alice", }

Single quotes:

// Invalid
{ 'name': 'Alice' }

Unquoted keys:

// Invalid
{ name: "Alice" }

Comments:

// Invalid - JSON doesn't support comments
{
    "name": "Alice"  // This is Alice's name
}

Valid JSON Example

{
    "user": {
        "id": 123,
        "username": "alice",
        "email": "alice@example.com",
        "verified": true,
        "age": 30,
        "bio": null,
        "roles": ["admin", "editor"],
        "settings": {
            "theme": "dark",
            "notifications": true
        }
    }
}

Validation

Check JSON validity:

try {
    JSON.parse(jsonString);
    console.log("Valid JSON");
} catch (error) {
    console.log("Invalid JSON:", error.message);
}

Online validators: JSONLint

Use in APIs

HTTP API response:

fetch('/api/users/123')
    .then(response => response.json())
    .then(data => {
        console.log(data.name);  // Access key-value pair
    });

Further Reading

The official JSON specification defines the format precisely.

MDN's JSON documentation covers JavaScript's JSON methods.

RFC 8259 is the formal JSON standard.

JSON's key-value structure is simple but powers most web APIs.

0 comments

Leave a comment

Please note, comments need to be approved before they are published.