Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/replay/frontend/src/pages/output/flattenJson.ts
1030 views
1
export interface FlatJson extends FlattenJsonOptions {
2
id?: number;
3
content: string;
4
level: number;
5
highlighted?: boolean;
6
scrollIntoView?: boolean;
7
path: string;
8
}
9
10
interface FlattenJsonOptions {
11
key?: string;
12
index?: number;
13
showComma?: boolean;
14
type?: string;
15
isContent?: boolean;
16
}
17
18
export default function flattenJson(
19
data: any,
20
path = '',
21
level = 0,
22
options: FlattenJsonOptions = {},
23
): FlatJson[] {
24
const { key, index, showComma = false } = options;
25
const type = Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
26
27
if (typeof data === 'object') {
28
const isArray = type === 'array';
29
30
const results: FlatJson[] = [
31
{
32
content: isArray ? '[' : '{',
33
level,
34
key,
35
path,
36
},
37
];
38
const keys = Object.keys(data);
39
40
for (let idx = 0; idx < keys.length; idx += 1) {
41
const objKey = isArray ? idx : keys[idx];
42
let childPath = `${path}.${objKey}`;
43
if (isArray) childPath = path ? `${path}.[${objKey}]` : `[${objKey}]`;
44
else if ((objKey as string).includes('.')) {
45
childPath = `${path}["${objKey}"]`;
46
}
47
48
const flattenJsonOptions: FlattenJsonOptions = {
49
showComma: idx !== keys.length - 1,
50
isContent: true,
51
};
52
if (isArray) {
53
flattenJsonOptions.index = idx;
54
} else {
55
flattenJsonOptions.key = objKey as string;
56
}
57
const childRecords = flattenJson(data[objKey], childPath, level + 1, flattenJsonOptions);
58
results.push(...childRecords);
59
}
60
61
results.push({
62
content: isArray ? ']' : '}',
63
showComma,
64
level,
65
path,
66
});
67
return results;
68
}
69
70
const output: FlatJson = {
71
content: data,
72
level,
73
key,
74
index,
75
path,
76
showComma,
77
isContent: true,
78
type,
79
};
80
81
return [output];
82
}
83
84