MediumPro challengePythonJavaScriptTypeScript

Circular-Safe JSON Serialize

ObjectsJSONFunctions

Implement solve(obj, replacer) that serializes an object to a JSON string,
replacing circular references with the string "[Circular]".

A replacer is an optional array of keys to include (same as JSON.stringify's
second argument). Pass null to include all keys.

Example

const a = { x: 1 };
a.self = a;
solve(a, null)  // '{"x":1,"self":"[Circular]"}'

Sample tests

Test #1Simple non-circular object
Input: [{"a":1,"b":2},null]
Output: "{\"a\":1,\"b\":2}"
Test #2Replacer filters to key "a" only
Input: [{"a":1},["a"]]
Output: "{\"a\":1}"
Test #3Nested object, no circular
Input: [{"x":1,"y":{"z":2}},null]
Output: "{\"x\":1,\"y\":{\"z\":2}}"
Test #4Empty replacer allowlist → only the root {} is kept
Input: [{"a":1},[]]
Output: "{}"
Test #5Flat object with number value
Input: [{"n":42},null]
Output: "{\"n\":42}"