Magicsheet logo

Convert JSON String to Object

Hard
87.5%
Updated 8/1/2025

Asked by 2 Companies

Topics

Convert JSON String to Object

What is this problem about?

The Convert JSON String to Object interview question is a classic parsing problem that requires you to implement a custom JSON parser. You are given a string representing a JSON object and must return its equivalent data structure (like a Map or Dictionary in your language of choice). This includes handling various data types such as nested objects, arrays, strings, numbers, booleans, and null values. Unlike using a built-in library like JSON.parse() in JavaScript, this task forces you to manually manage the state of the parser as it traverses the characters.

Why is this asked in interviews?

Companies like MongoDB and Verizon ask the Convert JSON String to Object coding problem to assess a candidate's mastery of recursion and state machines. It’s a "Hard" problem because it requires extreme attention to detail. You must handle complex scenarios like escaped characters in strings, floating-point numbers, and deeply nested structures. It demonstrates your ability to write robust, error-resistant code that can handle malformed input gracefully.

Algorithmic pattern used

The primary interview pattern for this problem is a Recursive Descent Parser. You maintain a pointer (or index) to the current character being processed. Depending on what character the pointer is on, you call a specialized function:

  • { calls parseObject()
  • [ calls parseArray()
  • " calls parseString()
  • t, f, or n call parseLiteral() (for true, false, null)
  • A digit or - calls parseNumber()

Example explanation

Input: {"id": 101, "tags": ["tech", "coding"]}

  1. The parser sees {, identifying an object.
  2. It moves to "id". parseString() is called to extract the key "id".
  3. It sees :, then 101. parseNumber() is called to convert the string "101" to an integer.
  4. It sees ,, then "tags". parseString() extracts the key "tags".
  5. It sees :, then [. parseArray() is called.
  6. Inside parseArray(), it sees "tech", calls parseString(), and adds it to a list.
  7. It repeats for "coding", then sees ], finishing the array.
  8. It sees }, finishing the object.

Common mistakes candidates make

  • Ignoring Escaped Characters: Not handling " or `` inside a string correctly.
  • Handling Whitespace: Failing to skip spaces, tabs, and newlines between keys and values.
  • Number Parsing: Missing the edge cases for negative numbers or floating points (e.g., -12.34).
  • Memory Management: Forgetting to handle deeply nested objects, which could lead to stack overflow if not careful.

Interview preparation tip

Practice implementing a smaller version first—just strings and numbers. Once you have the basic recursive structure, adding support for arrays and objects becomes much easier.

Similar Questions