CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-safe-stable-stringify

Deterministic and safely JSON.stringify to quickly serialize JavaScript objects

90

1.08x

Evaluation90%

1.08x

Agent success when using this tile

Overview
Eval results
Files

task.mdevals/scenario-7/

JSON Data Validator

Build a JSON data validator that ensures only valid JSON-representable data is serialized. The validator should reject invalid data with clear error messages before any API transmission occurs.

Requirements

Create a validator.js module that exports a validateAndSerialize function with the following behavior:

  1. Strict Validation: The function must enforce strict JSON compliance by throwing errors when encountering values that cannot be safely represented in JSON (functions, NaN, Infinity, -Infinity, top-level undefined).

  2. Deterministic Output: Successfully validated data should be serialized to JSON strings with consistent key ordering to ensure the same input always produces the same output.

  3. Circular Reference Rejection: The function should reject circular references by throwing errors rather than replacing them with placeholder strings.

The function should accept a single parameter (the data to validate) and return a JSON string if validation succeeds, or throw an error if validation fails.

Test Cases

Test Case 1: Valid Object @test

Input:

const data = { name: "Alice", age: 30, active: true };
const result = validateAndSerialize(data);

Expected Output: Returns a JSON string with keys in alphabetical order:

'{"active":true,"age":30,"name":"Alice"}'

Test Case 2: Invalid Function @test

Input:

const data = { name: "Bob", callback: function() {} };
validateAndSerialize(data);

Expected Output: Throws an error (function values are not valid JSON).

Test Case 3: Invalid NaN @test

Input:

const data = { value: NaN, id: 123 };
validateAndSerialize(data);

Expected Output: Throws an error (NaN is not valid JSON).

Test Case 4: Circular Reference @test

Input:

const data = { name: "test" };
data.self = data;
validateAndSerialize(data);

Expected Output: Throws an error (circular references are not valid JSON).

Test File

Create a test file validator.test.js that validates all test cases above.

Dependencies { .dependencies }

safe-stable-stringify { .dependency }

Provides safe and deterministic JSON serialization with validation capabilities.

Install with Tessl CLI

npx tessl i tessl/npm-safe-stable-stringify

tile.json