JSON
dynamic programming
data structures
coding tutorial
JavaScript

How to dynamically build a JSON object?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Dynamically building a JSON object is a common backend and frontend task when fields depend on user input, feature flags, or optional data. The safest approach is to build regular language-native objects first, validate values, and serialize at the end. This keeps data construction clear and avoids malformed payloads.

Build Dynamic JSON in JavaScript with Conditional Properties

In JavaScript, JSON payloads are usually built as plain objects. You can add keys progressively based on runtime conditions.

javascript
1function buildUserPayload(input) {
2  const payload = {
3    id: input.id,
4    email: input.email,
5  };
6
7  if (input.name) payload.name = input.name;
8  if (input.age !== undefined) payload.age = input.age;
9  if (Array.isArray(input.tags) && input.tags.length > 0) {
10    payload.tags = input.tags;
11  }
12
13  return payload;
14}
15
16const payload = buildUserPayload({
17  id: 1001,
18  email: "[email protected]",
19  name: "Ava",
20  tags: ["beta", "admin"],
21});
22
23console.log(JSON.stringify(payload, null, 2));

This pattern keeps optional keys out of the final JSON when no value exists.

For nested structures, initialize parent objects before adding child values.

javascript
1const order = { id: "ORD-1" };
2order.customer = {};
3order.customer.name = "Liam";
4order.customer.address = { city: "Montreal", country: "CA" };

Use Object Spread for Composable Payloads

Object spread makes dynamic construction cleaner when you merge optional sections.

javascript
1function buildOrder(input) {
2  return {
3    orderId: input.orderId,
4    currency: input.currency || "USD",
5    ...(input.discountCode ? { discountCode: input.discountCode } : {}),
6    ...(input.shipping
7      ? {
8          shipping: {
9            method: input.shipping.method,
10            priority: Boolean(input.shipping.priority),
11          },
12        }
13      : {}),
14  };
15}

This is concise, but use it carefully in large payload builders so readability stays high.

Build JSON in Python for API Calls

The same concept applies in Python. Build a dict, then serialize with json.dumps.

python
1import json
2
3
4def build_config(env, debug=False, timeout=None):
5    cfg = {
6        "env": env,
7        "retries": 3,
8    }
9
10    if debug:
11        cfg["debug"] = True
12    if timeout is not None:
13        cfg["timeout"] = timeout
14
15    return cfg
16
17
18payload = build_config("prod", debug=True, timeout=15)
19print(json.dumps(payload, indent=2))

For deeply nested data, helper functions make code easier to test.

python
1def make_db_section(host, port):
2    return {
3        "database": {
4            "host": host,
5            "port": port,
6        }
7    }
8
9cfg = {"service": "billing"}
10cfg.update(make_db_section("db.internal", 5432))

Validate Before Serializing

Dynamic payloads often fail because required fields are missing or value types are wrong. Validate object shape before converting to JSON.

JavaScript example:

javascript
1function validateUserPayload(payload) {
2  if (!payload.id) throw new Error("id is required");
3  if (!payload.email) throw new Error("email is required");
4  if (payload.age !== undefined && typeof payload.age !== "number") {
5    throw new Error("age must be a number");
6  }
7}

Python example:

python
1def validate_payload(payload):
2    required = ["env", "retries"]
3    for k in required:
4        if k not in payload:
5            raise ValueError(f"missing required key: {k}")

Validation before serialization catches data issues earlier and improves API reliability.

Serialize and Log Predictably

When debugging dynamic builders, stable serialization helps compare payloads across runs.

python
json.dumps(payload, sort_keys=True)
javascript
JSON.stringify(payload, Object.keys(payload).sort(), 2)

For production logs, avoid printing secrets. Redact tokens and passwords before logging.

Common Pitfalls

A common mistake is manually concatenating strings to produce JSON text. This is error-prone and can break escaping rules. Build objects first, then serialize with language libraries.

Another issue is including keys with undefined values unintentionally in JavaScript logic flow. Explicit conditions make payload shape predictable.

Developers also skip schema validation and only discover malformed JSON after an API rejects the request. Add validation right after building the object.

Summary

  • Build native objects or dictionaries first, then serialize to JSON.
  • Add optional fields conditionally to keep payloads clean.
  • Use helper functions for nested sections and reuse.
  • Validate required keys and value types before serialization.
  • Log payloads safely with stable formatting and secret redaction.

Course illustration
Course illustration

All Rights Reserved.