more robust json parsing
Browse files
src/lib/components/MonsterGenerator/MonsterGenerator.svelte
CHANGED
|
@@ -355,8 +355,27 @@ Assistant: \`\`\`json`;
|
|
| 355 |
}
|
| 356 |
|
| 357 |
try {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
const parsedStats = JSON.parse(cleanJson.trim());
|
| 359 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
// Ensure numeric fields are actually numbers
|
| 361 |
const numericFields = ['rarity', 'HP', 'defence', 'attack', 'speed'];
|
| 362 |
|
|
|
|
| 355 |
}
|
| 356 |
|
| 357 |
try {
|
| 358 |
+
// Remove any trailing text after the JSON object
|
| 359 |
+
const jsonMatch = cleanJson.match(/^\s*\{[\s\S]*?\}\s*/);
|
| 360 |
+
if (jsonMatch) {
|
| 361 |
+
cleanJson = jsonMatch[0];
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
const parsedStats = JSON.parse(cleanJson.trim());
|
| 365 |
|
| 366 |
+
// Remove any extra fields not in our schema
|
| 367 |
+
const allowedFields = ['name', 'description', 'rarity', 'HP', 'defence', 'attack', 'speed',
|
| 368 |
+
'specialPassiveTraitDescription', 'attackActionName', 'attackActionDescription',
|
| 369 |
+
'buffActionName', 'buffActionDescription', 'debuffActionName', 'debuffActionDescription',
|
| 370 |
+
'specialActionName', 'specialActionDescription', 'boostActionName', 'boostActionDescription',
|
| 371 |
+
'disparageActionName', 'disparageActionDescription'];
|
| 372 |
+
|
| 373 |
+
for (const key in parsedStats) {
|
| 374 |
+
if (!allowedFields.includes(key)) {
|
| 375 |
+
delete parsedStats[key];
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
// Ensure numeric fields are actually numbers
|
| 380 |
const numericFields = ['rarity', 'HP', 'defence', 'attack', 'speed'];
|
| 381 |
|