/** * Convert TypeScript object (or JavaScript object) to JSON. * * Usage: * This code uses Bun for execution, but it can also be run with other tools like Node.js. * * Example: * bun convert-ts-obj-to-json.ts * * Note: * The output file (output-file.json) will be created in the same directory as the input file. */ import * as fs from 'fs'; import * as path from 'path'; import * as ts from 'typescript'; const args = process.argv.slice(2); if (args.length === 0) { console.error('Error: No input file specified.'); process.exit(1); } const inputFilePath = path.resolve(process.cwd(), args[0]); const outputFilePath = path.join(path.dirname(inputFilePath), path.basename(inputFilePath, '.ts') + '.json'); const convertTsObjectToJson = (inputFile: string, outputFile: string) => { if (!fs.existsSync(inputFile)) { console.error(`Error: File not found: ${inputFile}`); process.exit(1); } const tsCode = fs.readFileSync(inputFile, 'utf8'); const sourceFile = ts.createSourceFile(inputFile, tsCode, ts.ScriptTarget.ESNext, true); let jsonObject: any = null; ts.forEachChild(sourceFile, (node) => { if ( ts.isExportAssignment(node) && ts.isObjectLiteralExpression(node.expression) ) { jsonObject = extractObject(node.expression); } }); if (jsonObject === null) { console.error('Error: No object literal found in the input file.'); process.exit(1); } fs.writeFileSync(outputFile, JSON.stringify(jsonObject, null, 2), 'utf8'); console.log(`Converted TypeScript object to JSON: ${outputFile}`); } const extractObject = (objectNode: ts.ObjectLiteralExpression): any => { const result: any = {}; objectNode.properties.forEach((prop) => { if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) { const key = prop.name.text; if (ts.isObjectLiteralExpression(prop.initializer)) { result[key] = extractObject(prop.initializer); } else if (ts.isStringLiteral(prop.initializer)) { result[key] = prop.initializer.text; } } }); return result; } // main convertTsObjectToJson(inputFilePath, outputFilePath);