Skip to main content

Convert Object to JSON String - Solution & Explanation

MediumPremiumFree on FleetCode3 min readAsked at: Apple, Google
Practice this problem

Problem Statement

Given a value, return a valid JSON string of that value. The value can be a string, number, array, object, boolean, or null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by Object.keys().

Please solve it without using the built-in JSON.stringify method.

 

Example 1:

Input: object = {"y":1,"x":2}
Output: {"y":1,"x":2}
Explanation: 
Return the JSON representation.
Note that the order of keys should be the same as the order returned by Object.keys().

Example 2:

Input: object = {"a":"str","b":-12,"c":true,"d":null}
Output: {"a":"str","b":-12,"c":true,"d":null}
Explanation:
The primitives of JSON are strings, numbers, booleans, and null.

Example 3:

Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}}
Output: {"key":{"a":1,"b":[{},null,"Hello"]}}
Explanation:
Objects and arrays can include other objects and arrays.

Example 4:

Input: object = true
Output: true
Explanation:
Primitive types are valid inputs.

 

Constraints:

  • value is a valid JSON value
  • 1 <= JSON.stringify(object).length <= 105
  • maxNestingLevel <= 1000
  • all strings contain only alphanumeric characters

Approach Overview

Problem Overview: Given a JavaScript object containing values like numbers, strings, booleans, arrays, nested objects, and null, generate a valid JSON string representation without using JSON.stringify. The serializer must handle nested structures and produce correctly formatted JSON.

Approach 1: Built-in Serialization (Baseline) (O(n) time, O(n) space)

The simplest way to convert an object to JSON is calling JSON.stringify(obj). The runtime internally traverses the object graph, serializes primitives, and recursively processes arrays and nested objects. Every element or property is visited once, so the time complexity is O(n) where n is the total number of values in the structure. The resulting string requires O(n) space. This approach works in real applications but is disallowed in this problem because the goal is implementing the serializer logic manually.

Approach 2: Recursive Object Traversal (O(n) time, O(n) space)

The expected solution walks the structure recursively and builds the JSON string step by step. Check the value type first. If the value is null, return the literal "null". For numbers and booleans, convert them directly using string conversion. For strings, wrap the value in double quotes.

Arrays require iterating through each element, recursively serializing them, and joining the results with commas inside square brackets. Objects require iterating over their key-value pairs, converting the key to a quoted string, serializing the value recursively, and joining pairs with commas inside curly braces. Each recursive call processes one element of the structure, which makes the traversal linear.

The key insight: treat arrays and objects as containers and delegate serialization of their contents back to the same function. This recursive pattern mirrors how JSON structures are nested. Each value is processed exactly once, leading to O(n) time complexity. The output string and recursion stack together require O(n) space.

This pattern appears frequently in problems involving tree-like or nested data structures. Understanding recursive traversal helps with tasks like AST processing, deep cloning, and parsing. Related techniques appear in recursion, nested structure traversal, and string construction problems.

Recommended for interviews: The recursive traversal approach is what interviewers expect. Mentioning the built-in serializer shows awareness of practical JavaScript, but implementing the recursion demonstrates understanding of nested structures and algorithmic reasoning.

Solution

Code

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Built-in JSON.stringifyO(n)O(n)Real-world applications where built-in serialization is allowed
Recursive Object TraversalO(n)O(n)Interview problems requiring manual JSON serialization

Video Solution

Convert Object to JSON String - Leetcode 2633 - JavaScript 30-Day Challenge • NeetCodeIO • 6,092 views views

Watch 4 more video solutions →

Frequently Asked Questions

Is Convert Object to JSON String easy or hard?
The problem is rated Medium because it requires careful handling of multiple data types and nested structures. The recursion itself is straightforward, but correctly formatting arrays, objects, and strings without using built-in serializers adds complexity.
Convert Object to JSON String Python/Java solution
The same idea applies across languages. Implement a recursive function that checks the value type, serializes primitives, iterates arrays, and processes object/dictionary entries. Each language builds the final string using concatenation or join operations.
How to solve Convert Object to JSON String in O(n)?
Use a recursive function that serializes values based on their type. Convert primitives directly, iterate through arrays and recursively serialize elements, and iterate through object keys to serialize key-value pairs. Because each node in the structure is visited once, the overall complexity remains O(n).
What is the best approach for Convert Object to JSON String?
The best approach is recursive traversal of the object structure. Check the type of each value, directly serialize primitives, and recursively process arrays and nested objects. Every element is visited once, producing an O(n) time solution with O(n) space for the output string and recursion stack.
Is Convert Object to JSON String asked at Google/Amazon/Meta?
Serialization and nested data traversal problems frequently appear in interviews at large tech companies. Variants of custom JSON serialization test recursion, type handling, and string construction skills often evaluated in frontend and full‑stack interviews.
What data structure is used in Convert Object to JSON String?
The solution operates on nested JavaScript objects and arrays. Recursion is used to traverse the structure, and strings are incrementally constructed to build the final JSON representation.
What is the time complexity of Convert Object to JSON String?
The time complexity is O(n), where n is the total number of values and properties in the object structure. Each element, array entry, or object key-value pair is processed exactly once during the recursive traversal.

Ready to solve this problem?

Practice Convert Object to JSON String with our built-in code editor and test cases.

Practice on FleetCode