Convert and object to a JSON string without built in methods
Given an object, return a valid JSON string of that object. You may assume the object only inludes strings, integers, arrays, objects, booleans, and 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.
function jsonStringify(object: any): string {
if (object === null) {
return 'null';
}
if (typeof object === 'string') {
return `"${object}"`;
}
if (typeof object === 'number' || typeof object === 'boolean') {
return object.toString();
}
if (Array.isArray(object)) {
return `[${object.map(jsonStringify).join(',')}]`;
}
if (typeof object === 'object') {
return `{${Object.entries(object)
.map(
([key, value]) =>
`${jsonStringify(key)}:${jsonStringify(value)}`,
)
.join(',')} }`;
}
return '';
}
def json_stringify(obj):
if obj is None:
return 'null'
if isinstance(obj, str):
return f'"{obj}"'
# Numbers and Booleans can be converted to string directly.
if isinstance(obj, (int, float, bool)):
return str(obj)
# Lists are processed recursively, with each element being converted and joined by commas.
if isinstance(obj, list):
list_elements = [json_stringify(element) for element in obj]
return '[' + ','.join(list_elements) + ']'
# Dictionaries are processed by converting each key-value pair and joining them by commas.
if isinstance(obj, dict):
dict_entries = [f'{json_stringify(key)}:{json_stringify(value)}' for key, value in obj.items()]
return '{' + ','.join(dict_entries) + '}'
# Fallback for unsupported types: return an empty string.
return ''
To manually convert an object literal into a JSON serialized string, you can use a recursive function that processes each key-value pair in the object. The idea is to traverse the object and handle each value according to its type. For arrays, you'd recursively process each element and build the serialized string. For object literals, you would do the same but with each key and value pair, ensuring that the key is wrapped in quotes and separated from its value with a colon. Primitive types like strings, numbers, and booleans can be added directly, with strings requiring quotes.
Handling unsupported types, such as functions or undefined values, is an important consideration. You might choose to either skip them or use a fallback, such as converting them to null, depending on the behavior you want. Alternatively, you could throw an error when encountering an unsupported type. This recursive approach allows for flexibility in how objects are serialized while adhering to the JSON format's rules, ensuring that arrays, objects, and other serializable types are handled properly.
Related Problems
The Hamming Distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Given an array of asyncronous functions functions and a pool limit n, return an asyncronous function promisePool. It should return a promise that resolves when all the input functions resolve.
Pool limit is defined as the maximum number promises that can be pending at once. promisePool should begin execution of as many functions as possible and continue executing new functions when old promises resolve. promisePool should execute functions[i] then functions[i + 1] then functions[i + 2], etc. When the last promise resolves, promisePool should also resolve.
For example, if n = 1, promisePool will execute one function at a time in series. However, if n = 2, it first executes two functions. When either of the two functions resolve, a 3rd function should be executed (if available), and so on until there are no functions left to execute.
You can assume all functions never reject. It is acceptable for promisePool to return a promise that resolves any value.
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.