2633. Convert Object to JSON String - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

Description:
Implement a function that converts a given object into its JSON string representation. The object can be one of the following types:

  • Null: represented as null

  • Boolean: represented as true or false

  • Number: (integer or float) represented in numeric format

  • String: must be enclosed in double quotes and properly escaped

  • Array: represented as a list of JSON values, separated by commas, and enclosed in square brackets []

  • Object: represented as key-value pairs (with keys always being strings), separated by commas, and enclosed in curly braces {}

Examples:

  • Example 1:
    Input: obj = "Hello"
    Output: "\"Hello\""
    Explanation:
    A string should be output with double quotes around it.

  • Example 2:
    Input: obj = 123
    Output: "123"
    Explanation:
    A number is represented directly as its string form.

  • Example 3:
    Input: obj = [1, "two", null, true]
    Output: "[1,\"two\",null,true]"
    Explanation:
    The array elements are recursively converted to their JSON string representations and then joined with commas, enclosed in square brackets.

  • Example 4:
    Input:

    { "name": "Alice", "age": 30, "pets": ["cat", "dog"], "address": null }

    Output:
    "{"name":"Alice","age":30,"pets":["cat","dog"],"address":null}"
    Explanation:
    Each key (always a string) and its corresponding value are recursively converted and formatted into a valid JSON object.

Constraints:

  • The input can be a nested structure with any combination of the supported types.
  • All keys in objects are strings.
  • Proper escaping of characters in strings is required (e.g., quotes).

Hints

  • Hint 1: Think recursively. Determine the type of the given object and handle it based on its type.
  • Hint 2: For arrays and objects, you will need to iterate over elements or key–value pairs, convert each one using your function recursively, and then join them with the appropriate separators.
  • Hint 3: Make sure to handle edge cases such as null values and proper string escaping.

Approaches

Recursive Serialization (Optimal Approach)

Concept:

  • Base Cases:
    Check if the object is null, a boolean, a number, or a string. Return the proper JSON representation:
    • null"null"
    • Boolean → "true" or "false"
    • Number → its string conversion
    • String → enclosed in double quotes with proper escaping (if needed)
  • Recursive Cases:
    • Arrays:
      Iterate over each element, recursively convert each one to JSON, join the results with commas, and enclose in square brackets.
    • Objects (Dictionaries):
      Iterate over each key–value pair, recursively convert the value to JSON (the key is always a string, so ensure it’s enclosed in double quotes), join with commas, and enclose in curly braces.

Benefits:

  • The recursive approach naturally handles nested structures.
  • Each type is dealt with in a clear, modular way.

Alternative Approach – Using Built-In Library (Not Allowed Here)

Concept:

  • In many languages, you could simply call a built-in method (e.g., JSON.stringify() in JavaScript or json.dumps() in Python).
  • Note: This approach is trivial but is not acceptable if you are required to implement the conversion logic manually.

Code Implementations

Python Code (Recursive Approach)

Python3
Python3

. . . .

Java Code (Recursive Approach)

Java
Java

. . . .

Step-by-Step Walkthrough and Visual Example

Consider converting the following object to a JSON string:

{ "name": "Alice", "age": 30, "pets": ["cat", "dog"], "address": null }

Step 1: Object (Dictionary / Map)

  • Iterate over each key–value pair:
    • Key: "name" → already a string → becomes "\"name\""
    • Value: "Alice" → becomes "\"Alice\""
    • Key: "age" → becomes "\"age\""
    • Value: 30 → becomes "30"
    • Key: "pets" → becomes "\"pets\""
    • Value: an array ["cat", "dog"]
    • Key: "address" → becomes "\"address\""
    • Value: null → becomes "null"

Step 2: Array Conversion

  • For the "pets" array:
    • Each element is processed:
      • "cat" → becomes "\"cat\""
      • "dog" → becomes "\"dog\""
    • Join these with commas and enclose in square brackets → "[\"cat\",\"dog\"]"

Step 3: Reassemble the Object

  • Combine each key and its corresponding JSON-converted value with a colon.
  • Join all pairs with commas and enclose in curly braces.

Final JSON String:

{"name":"Alice","age":30,"pets":["cat","dog"],"address":null}

Common Mistakes

  • Improper Escaping in Strings:
    Forgetting to escape quotes or other special characters can lead to invalid JSON.

  • Missing Type Checks:
    Not handling every supported type (or encountering an unsupported type) can result in errors.

  • Not Handling Arrays or Objects Recursively:
    Failing to apply the conversion recursively for nested structures will yield incorrect results.

Edge Cases and Alternative Variations

Edge Cases:

  • Empty Array or Object:
    Ensure that an empty list returns "[]" and an empty dictionary returns "{}".

  • Nested Structures:
    Deeply nested arrays or objects should be handled correctly by recursion.

  • Special Characters in Strings:
    Strings containing quotes, backslashes, or control characters must be properly escaped.

Variations:

  • Pretty-Printed JSON:
    Instead of a compact format, you could add indentation and line breaks for human-readable output.

  • Extended Type Handling:
    Supporting additional types (like Date objects) may require custom serialization logic.

  • Implementing a Basic XML Serializer

  • Parsing JSON Strings into Objects (deserialization)

  • Designing Custom Data Serialization Formats

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How do I improve my Java coding skills?
How do I start coding DSA?
Aligning system design choices with business objectives
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;