MCPcopy Create free account
hub / github.com/triggerdotdev/jsonhero-web / stableJson

Function stableJson

app/utilities/stableJson.ts:1–43  ·  view source on GitHub ↗
(json: unknown, keyOrder: string[] = [])

Source from the content-addressed store, hash-verified

1export function stableJson(json: unknown, keyOrder: string[] = []): unknown {
2 if (
3 Array.isArray(json) &&
4 json.length > 0 &&
5 json.every((c) => typeof c === "object" && c !== null)
6 ) {
7 const keyOrder = Object.keys(json[0]);
8 return json.map((c) => stableJson(c, keyOrder));
9 }
10
11 if (Array.isArray(json)) {
12 return json.map((c) => stableJson(c));
13 }
14
15 if (typeof json === "object" && json !== null && keyOrder.length > 0) {
16 const keys = Object.keys(json);
17 const sortedKeys = keys.sort((a, b) => {
18 const aIndex = keyOrder.indexOf(a);
19 const bIndex = keyOrder.indexOf(b);
20
21 if (aIndex === -1 || bIndex === -1) {
22 return 0;
23 }
24
25 return aIndex - bIndex;
26 });
27 const result = {} as Record<string, unknown>;
28 for (const key of sortedKeys) {
29 result[key] = stableJson((json as Record<string, unknown>)[key]);
30 }
31 return result;
32 }
33
34 if (typeof json === "object" && json !== null) {
35 const result = {} as Record<string, unknown>;
36 for (const key of Object.keys(json)) {
37 result[key] = stableJson((json as Record<string, unknown>)[key]);
38 }
39 return result;
40 }
41
42 return json;
43}

Callers 2

JsonProviderFunction · 0.90
stableJson.test.tsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected