Implement a function jsonStringify(object)
that converts a JavaScript object into a JSON string. You cannot use the built-in JSON.stringify()
method.
The function should handle the following data types:
NaN
and Infinity
)Special considerations:
undefined
values in objects should be excluded from the final JSON string.NaN
and Infinity
should be represented as null
.Example:
const obj = { a: 1, b: "hello", c: [true, false, null] };
jsonStringify(obj); // Output: '{"a":1,"b":"hello","c":[true,false,null]}'
const arr = [1, "world", { x: null }];
jsonStringify(arr); // Output: '[1,"world",{"x":null}]'
const circularObj = { };
circularObj.myself = circularObj;
jsonStringify(circularObj); // Output: '{\"myself\":\"[Circular]\
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to converting an object to a JSON string involves handling each possible data type separately and recursively. It essentially inspects every field in the object and transforms it based on its type. This method explores all potential string representations until the entire object is converted.
Here's how the algorithm would work step-by-step:
def convert_to_json_string(object_to_convert):
if object_to_convert is None:
return "null"
if isinstance(object_to_convert, bool):
return "true" if object_to_convert else "false"
if isinstance(object_to_convert, (int, float)): # Numbers are converted directly
return str(object_to_convert)
if isinstance(object_to_convert, str):
return '"' + object_to_convert + '"'
if isinstance(object_to_convert, list):
list_elements = []
for element in object_to_convert:
list_elements.append(convert_to_json_string(element))
return '[' + ','.join(list_elements) + ']'
if isinstance(object_to_convert, dict):
# Dictionaries need special formatting of keys and values
dictionary_elements = []
for key, value in object_to_convert.items():
key_string = convert_to_json_string(key)
value_string = convert_to_json_string(value)
dictionary_elements.append(key_string + ':' + value_string)
# Construct the JSON representation of the dictionary
return '{' + ','.join(dictionary_elements) + '}'
# Raise exception in case we cannot serialize the given object
raise TypeError(f"Object of type '{type(object_to_convert).__name__}' is not JSON serializable")
To transform an object into a text format resembling its structure, we need to handle different types of data within the object. The best approach is to systematically examine each part of the object and convert it into the correct text representation while following specific formatting rules.
Here's how the algorithm would work step-by-step:
def convert_object_to_json_string(object_to_convert):
if object_to_convert is None:
return "null"
object_type = type(object_to_convert)
if object_type is str:
return '"' + object_to_convert + '"'
elif object_type is int or object_type is float or object_type is bool:
return str(object_to_convert)
elif object_type is list:
# Recursively convert each list element to JSON.
json_list = [convert_object_to_json_string(item) for item in object_to_convert]
return '[' + ','.join(json_list) + ']'
elif object_type is dict:
# This block handles dictionaries/objects.
json_pairs = []
for key, value in object_to_convert.items():
json_key = convert_object_to_json_string(key)
json_value = convert_object_to_json_string(value)
json_pairs.append(json_key + ':' + json_value)
# Join key-value pairs with commas, enclose in curly braces.
return '{' + ','.join(json_pairs) + '}'
else:
return '"' + str(object_to_convert) + '"'
Case | How to Handle |
---|---|
Null or undefined object input | Return 'null' string to represent null/undefined objects in JSON. |
Empty object input ({}) | Return '{}' to represent an empty JSON object. |
Object with circular references | Detect cycles using a Set to track visited objects and throw an error or return 'null' to prevent infinite recursion. |
Object containing primitive types (string, number, boolean, null) | Convert primitive values directly to their JSON representation (e.g., number to string, true to 'true'). |
Object containing arrays of different data types | Recursively convert array elements to their JSON representations, handling nested objects and arrays. |
Object with properties containing special characters (e.g., quotes, backslashes, newline) | Properly escape special characters in property names and string values using backslashes. |
Object with Date objects | Convert Date objects to their ISO string representation using toISOString(). |
Large object with many nested levels | Implement iterative solution to avoid stack overflow errors or limit the recursion depth and return an error. |