split
Divide a JSON file into a specified number of objects for easier processing or analysis. Input the file path and the desired number of objects to split the content efficiently.
Instructions
Split a JSON file into a specified number of objects
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| numObjects | Yes | ||
| path | Yes |
Implementation Reference
- src/index.ts:161-208 (handler)The handler for the 'split' tool. It validates input, reads a JSON file, splits its array into multiple files each containing up to numObjects items, writes them as part1.json, part2.json etc., and returns a success message.case 'split': { const parsed = SplitArgSchema.safeParse(args) if (!parsed.success) { throw new Error(`Invalid arguments for split: ${parsed.error}`) } const { path, numObjects } = parsed.data const validPath = await validatePath(path) const content = await fs.promises.readFile(validPath, 'utf-8') const folder = await getParentDir(path) const jsonData = JSON.parse(content) if (numObjects >= jsonData.length / 2) { throw new Error( `The number of objects (${numObjects}) per file cannot be half or more of the total (${jsonData.length}) JSON data length.` ) } const totalParts = Math.ceil(jsonData.length / numObjects) await Promise.all( Array.from({ length: totalParts }, async (_, i) => { const partArray = jsonData .slice(i * numObjects, (i + 1) * numObjects) ?.flat() const partFileName = _path.join(folder, `part${i + 1}.json`) try { await fs.promises.writeFile( partFileName, JSON.stringify(partArray, null, 2) ) console.log(`Successfully wrote ${partFileName}`) } catch (err) { console.error(`Error writing file ${partFileName}:`, err) } }) ) return { content: [ { type: 'text', text: `Successfully splitted to ${parsed.data.path}`, }, ], } }
- src/index.ts:43-46 (schema)Zod schema defining the input arguments for the split tool: path (string) and numObjects (positive integer).const SplitArgSchema = z.object({ path: z.string(), numObjects: z.number().int().positive(), })
- src/index.ts:142-146 (registration)Registration of the 'split' tool in the ListTools response, including name, description, and input schema.{ name: 'split', description: 'Split a JSON file into a specified number of objects', inputSchema: zodToJsonSchema(SplitArgSchema) as ToolInput, },