Convert JSON String to Object Problem
Description
LeetCode Problem 2759.
Given a string str, return parsed JSON parsedStr. You may assume the str is a valid JSON string hence it only includes strings, numbers, arrays, objects, booleans, and null. str will not include invisible characters and escape characters.
Please solve it without using the built-in JSON.parse method.
Example 1:
Input: str = '{"a":2,"b":[1,2,3]}'
Output: {"a":2,"b":[1,2,3]}
Explanation: Returns the object represented by the JSON string.
Example 2:
Input: str = 'true'
Output: true
Explanation: Primitive types are valid JSON.
Example 3:
Input: str = '[1,5,"false",{"a":2}]'
Output: [1,5,"false",{"a":2}]
Explanation: Returns the array represented by the JSON string.
Constraints:
stris a valid JSON string1 <= str.length <= 10^5
Solution
Approach: Recursive descent parser
Write a small recursive-descent parser with one index i into the string. parseValue looks at the current character and dispatches:
{parses an object: read a string key, skip:, parse a value, then skip,until}.[parses an array: parse values separated by,until]."reads characters up to the closing quote.t,f,naretrue,false,null, of fixed length 4, 5, 4.- anything else is a number: consume characters that can appear in one (
-,+,.,e,E, digits) and convert withNumber.
Each parse function leaves i just after what it consumed, so the callers need no bookkeeping. The input is guaranteed valid and free of whitespace and escapes, so no error handling is needed.
Complexity: Time O(n), space O(d) recursion depth for nesting depth d (plus the output).
/**
* @param {string} str
* @return {null|boolean|number|string|Array|Object}
*/
var jsonParse = function (str) {
let i = 0;
const parseValue = () => {
const c = str[i];
if (c === '{') return parseObject();
if (c === '[') return parseArray();
if (c === '"') return parseString();
if (c === 't') return (i += 4), true;
if (c === 'f') return (i += 5), false;
if (c === 'n') return (i += 4), null;
return parseNumber();
};
const parseNumber = () => {
const start = i;
while (i < str.length && /[-+.eE0-9]/.test(str[i])) i++;
return Number(str.slice(start, i));
};
const parseString = () => {
i++; // opening quote
const start = i;
while (str[i] !== '"') i++;
const s = str.slice(start, i);
i++; // closing quote
return s;
};
const parseArray = () => {
const arr = [];
i++; // [
while (str[i] !== ']') {
arr.push(parseValue());
if (str[i] === ',') i++;
}
i++; // ]
return arr;
};
const parseObject = () => {
const obj = {};
i++; // {
while (str[i] !== '}') {
const key = parseString();
i++; // :
obj[key] = parseValue();
if (str[i] === ',') i++;
}
i++; // }
return obj;
};
return parseValue();
};