Problem solution · TypeScript

Convert JSON String to Object

Convert JSON String to Object: a TypeScript solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Binary search
Source
walkccc LeetCode Solutions
Length
142 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For Convert JSON String to Object, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. Move the appropriate boundary after each midpoint check and return the final feasible position.

Code notes

  • 142 lines of TypeScript from the credited upstream file 2759.ts.
  • The implementation visibly relies on sequence storage.
  • 5 loop blocks detected.

Complexity

Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeConvert JSON String to Object · TypeScriptTypeScript
Use this to learn the idea, then write your own version.
type JSONValue =  | null  | boolean  | number  | string  | JSONValue[]  | { [key: string]: JSONValue }; class JSONParser {  private str: string;  private i: number;   constructor(str: string) {    this.str = str;    this.i = 0;  }   public parse(): JSONValue {    return this.parseValue();  }   private parseValue(): JSONValue {    switch (this.str[this.i]) {      case '{':        return this.parseObject();      case '[':        return this.parseArray();      case 't': // true      case 'f': // false      case 'n': // null        return this.parseLiteral();      case '"':        return this.parseString();      default:        return this.parseNumber();    }  }   private parseObject(): JSONValue {    ++this.i;     const ans: JSONValue = {};     while (this.i < this.str.length && this.str[this.i] !== '}') {      const key = this.parseString();      this.expectChar(':');      const value = this.parseValue();       ans[key] = value;      if (this.str[this.i] === ',') {        ++this.i;      }    }     ++this.i;    return ans;  }   private parseArray(): JSONValue[] {    ++this.i;     const ans: JSONValue[] = [];     while (this.i < this.str.length && this.str[this.i] !== ']') {      const value = this.parseValue();      ans.push(value);      if (this.str[this.i] === ',') {        ++this.i;      }    }     ++this.i;    return ans;  }   private parseLiteral(): boolean | null {    if (this.str.startsWith('true', this.i)) {      this.i += 4;      return true;    }    if (this.str.startsWith('false', this.i)) {      this.i += 5;      return false;    }    if (this.str.startsWith('null', this.i)) {      this.i += 4;      return null;    }    throw new Error(`Unexpected token at position ${this.i}`);  }   private parseString(): string {    let ans = '';    ++this.i;     while (this.i < this.str.length && this.str[this.i] !== '"') {      ans += this.str[this.i];      ++this.i;    }     ++this.i;    return ans;  }   private parseNumber(): number {    let start = this.i;     if (this.str[this.i] === '-') {      ++this.i;    }     while (this.i < this.str.length && this.isDigit(this.str[this.i])) {      ++this.i;    }     if (this.str[this.i] === '.') {      ++this.i;      while (this.i < this.str.length && this.isDigit(this.str[this.i])) {        ++this.i;      }    }     return Number(this.str.slice(start, this.i));  }   private isDigit(n: string): boolean {    return n >= '0' && n <= '9';  }   private expectChar(char: string): void {    if (this.str[this.i] !== char) {      throw new Error(`Expected '${char}' at position ${this.i}`);    }    ++this.i;  }} function jsonParse(str: string): JSONValue {  const parser = new JSONParser(str);  return parser.parse();} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗