MCPcopy Create free account
hub / github.com/Datakitpage/Datakit / flattenJSON

Function flattenJSON

frontend/src/hooks/stream/useStreamingJSONParser.ts:115–167  ·  view source on GitHub ↗
(json: any[])

Source from the content-addressed store, hash-verified

113 * Flatten JSON for tabular display
114 */
115 const flattenJSON = (json: any[]): [string[][], JsonSchema] => {
116 if (!json || json.length === 0) return [[], { properties: {}, isNested: false }];
117
118 // Collect all property names
119 const properties = new Set<string>();
120 for (const item of json) {
121 if (item && typeof item === 'object') {
122 Object.keys(item).forEach(key => properties.add(key));
123 }
124 }
125
126 // Create header row
127 const headers = Array.from(properties);
128 const rows: string[][] = [headers];
129
130 // Detect property types
131 const propertyTypes = detectPropertyTypes(json);
132
133 // Check if JSON is nested
134 const isNested = isNestedJSON(json);
135
136 // Build schema information
137 const schema: JsonSchema = {
138 properties: propertyTypes,
139 isNested
140 };
141
142 // Flatten each item into a row
143 for (const item of json) {
144 const row: string[] = [];
145
146 for (const prop of headers) {
147 if (item && typeof item === 'object' && prop in item) {
148 const value = item[prop];
149
150 if (value === null || value === undefined) {
151 row.push('');
152 } else if (typeof value === 'object') {
153 // For objects and arrays, convert to string representation
154 row.push(JSON.stringify(value));
155 } else {
156 row.push(String(value));
157 }
158 } else {
159 row.push('');
160 }
161 }
162
163 rows.push(row);
164 }
165
166 return [rows, schema];
167 };
168
169 /**
170 * Stream and parse a JSON file

Callers 2

parseJSONStreamFunction · 0.85
parseJsonTextFunction · 0.85

Calls 2

detectPropertyTypesFunction · 0.85
isNestedJSONFunction · 0.85

Tested by

no test coverage detected