We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Convert Object to JSON String

Number: 2745

Difficulty: Medium

Paid? Yes

Companies: Google


Problem Description

Given a value that can be a string, number, array, object, boolean, or null, return its valid JSON string representation. The output must not include any extra spaces, and for objects, the key order should follow the order returned by Object.keys(). You are not allowed to use the built-in JSON.stringify method.


Key Insights

  • The solution must support all JSON primitives: strings, numbers, booleans, and null.
  • Composite types such as arrays and objects require recursive traversal for proper serializing.
  • For strings, wrap them in double quotes.
  • For arrays, recursively process every element and join them with commas between square brackets.
  • For objects, iterate keys in insertion order and combine key-value pairs (key must be a string in double quotes) with commas between curly braces.
  • Use recursion carefully to handle nested structures without adding unnecessary spaces.

Space and Time Complexity

Time Complexity: O(n), where n is the total number of elements/characters in the JSON structure. Space Complexity: O(n) due to the recursion stack and the constructed output string.


Solution

We use a recursive approach that inspects the type of the value and processes it accordingly:

  1. If the value is null, output "null".
  2. If the value is a boolean or number, convert it directly to its string representation.
  3. For a string, ensure it is enclosed in double quotes.
  4. For an array, iterate over each element, serialize each recursively, join them with commas, and enclose in square brackets.
  5. For an object, iterate over its keys in insertion order (or using Object.keys in JS / LinkedHashMap in Java), serialize both key (wrapped in double quotes) and its corresponding value, join with commas, and enclose in curly braces. This approach leverages recursion to handle arbitrarily nested objects and arrays while ensuring there are no extra spaces in the final string.

Code Solutions

def myStringify(value):
    # If value is None, return "null"
    if value is None:
        return "null"
    # If value is a boolean, convert to "true" or "false"
    if isinstance(value, bool):
        return "true" if value else "false"
    # If value is a number, return its string representation
    if isinstance(value, (int, float)):
        return str(value)
    # If value is a string, enclose it in double quotes
    if isinstance(value, str):
        return '"' + value + '"'
    # If value is a list, recursively process its elements
    if isinstance(value, list):
        return '[' + ','.join(myStringify(item) for item in value) + ']'
    # If value is a dictionary, iterate keys in the order of insertion
    if isinstance(value, dict):
        items = []
        for key in value:
            items.append('"' + key + '":' + myStringify(value[key]))
        return '{' + ','.join(items) + '}'
    # Fallback (should not be reached with valid JSON types)
    return ""

# Example usage:
test_obj = {"y": 1, "x": 2}
print(myStringify(test_obj))
← Back to All Questions