Neural Mastery
← Practice
Recursive Pure-Python JSON Serializerhard

Recursive Pure-Python JSON Serializer

hard Python for AI 20–25 min

NumPy allowed · plain Python earns 10 bonus points

Implement recursive JSON serialization from scratch supporting nested objects, lists, escaping, and primitives.

Related Skills

Task

Implement custom_json_serializer(data): serialize Python primitives (None -> null, bool -> true/false, numbers, strings with escaped quotes/newlines, lists, and dicts) into standard JSON syntax without using the standard library json module.

Function Signature

custom_json_serializer(data: any) -> str

Examples

Example 1: Nested Dictionary with List
Input: data = {'name': 'Alice', 'scores': [95, 100], 'verified': True}
Output: '{"name": "Alice", "scores": [95, 100], "verified": true}'
Example 2: Null and Primitives
Input: data = [None, False, 3.14]
Output: '[null, false, 3.14]'
Example 3: String with Escapes
Input: data = {'quote': 'He said "hello"'}
Output: '{"quote": "He said \\"hello\\""}'

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • No use of json module.
  • Properly escapes quotes and backslashes in strings.
Python3Saved ✓
def custom_json_serializer(data: any) -> str:
"""Serialize primitive and nested Python data (None, bool, int, float, str, list, dict)
into a valid JSON string without using json.dumps()."""
# Your implementation here
pass

Case 1: Nested Dictionary with List
Input: data = {'name': 'Alice', 'scores': [95, 100], 'verified': True}
Expected: '{"name": "Alice", "scores": [95, 100], "verified": true}'
Case 2: Null and Primitives
Input: data = [None, False, 3.14]
Expected: '[null, false, 3.14]'
Case 3: String with Escapes
Input: data = {'quote': 'He said "hello"'}
Expected: '{"quote": "He said \\"hello\\""}'