fromJsonString static method
Imports from a JSON string
Implementation
static ImportResult fromJsonString(
String jsonContent, {
String schemaName = 'ImportedData',
}) {
try {
final decoded = jsonDecode(jsonContent);
List<Map<String, dynamic>> dataList;
if (decoded is List) {
dataList = decoded
.map((e) => Map<String, dynamic>.from(e as Map))
.toList();
} else if (decoded is Map) {
dataList = [Map<String, dynamic>.from(decoded)];
} else {
return ImportResult(
schema: _createEmptySchema(schemaName),
data: [],
rowCount: 0,
error: 'Invalid JSON format',
);
}
if (dataList.isEmpty) {
return ImportResult(
schema: _createEmptySchema(schemaName),
data: [],
rowCount: 0,
error: 'Empty JSON',
);
}
// Extract the fields from the first object
final firstItem = dataList.first;
final fields = <FieldDefinition>[];
firstItem.forEach((key, value) {
fields.add(
FieldDefinition(
name: key,
displayName: _formatDisplayName(key),
type: _inferType(value),
isRequired: false,
),
);
});
final schema = _ImportedDataSchema(
name: schemaName,
displayName: schemaName,
description: 'Schema imported from JSON',
fields: fields,
sampleData: firstItem,
);
return ImportResult(
schema: schema,
data: dataList,
rowCount: dataList.length,
);
} catch (e) {
return ImportResult(
schema: _createEmptySchema(schemaName),
data: [],
rowCount: 0,
error: 'Error parsing the JSON: $e',
);
}
}