ts-data-forge
    Preparing search index...

    Function stringifySortedKey

    • Safely converts a JavaScript record to a JSON string with keys sorted alphabetically at all levels.

      This function creates deterministic JSON output by ensuring that object keys appear in alphabetical order at every level of nesting. This is particularly useful for creating consistent output for comparison, hashing, caching, or when you need reproducible JSON representations across different JavaScript engines or runs.

      Parameters

      • value: UnknownRecord

        An object (UnknownRecord) to serialize. Must be a plain object (not an array, primitive, or null). Nested objects and arrays within the object will also have their keys sorted alphabetically.

      • Optionalspace: string | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10

        Optional formatting parameter:

        • Number (1-10): Number of spaces to indent each level
        • String: String to use for indentation (first 10 characters)
        • Undefined/null: No formatting (compact output)

      Returns Result<string, string>

      A Result<string, string> containing:

      • On success: Result.ok(jsonString) with all object keys sorted alphabetically
      • On failure: Result.err(errorMessage) describing the serialization error
      const unorderedData = {
      zebra: 1,
      apple: 2,
      mango: 3,
      nested: {
      zulu: 'z',
      alpha: 'a',
      beta: 'b',
      },
      };

      // Keys will be sorted alphabetically at all levels
      const sorted = Json.stringifySortedKey(unorderedData);

      assert.ok(Result.isOk(sorted));
      if (Result.isOk(sorted)) {
      // Keys should appear in alphabetical order
      const expected =
      '{"apple":2,"mango":3,"nested":{"alpha":"a","beta":"b","zulu":"z"},"zebra":1}';
      assert(sorted.value === expected);
      }

      // With formatting
      const formatted = Json.stringifySortedKey(unorderedData, 2);
      assert.ok(Result.isOk(formatted));
      if (Result.isOk(formatted)) {
      // Check that keys are in order (first key should be "apple")
      assert.ok(
      formatted.value.indexOf('"apple"') < formatted.value.indexOf('"mango"'),
      );
      assert.ok(
      formatted.value.indexOf('"mango"') < formatted.value.indexOf('"nested"'),
      );
      assert.ok(
      formatted.value.indexOf('"nested"') < formatted.value.indexOf('"zebra"'),
      );
      }