Last active
November 30, 2024 14:57
-
-
Save shinshin86/34966cd090852124ae0c8dc666f2c28f to your computer and use it in GitHub Desktop.
Convert TypeScript object to JSON. The output file (output-file.json) will be created in the same directory as the input file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 <input-file.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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment