To convert JSON to CSV in TypeScript, we need to read the data from a JSON file, transform the data into a CSV format, and write it to a CSV file. We will be using the fs
module to read and write files.
Here is an example TypeScript code to convert JSON to CSV:
index.ts736 chars35 lines
In this example, we define an interface Data
to represent the shape of each JSON object. We define a function jsonToCsv
that takes an array of JSON objects as input and returns a string of CSV data. The function first extracts the headers from the keys of the first JSON object. It then iterates over each JSON object and extracts the corresponding values for each header, formatting the values as necessary according to the rules of CSV. Finally, the function returns a string of CSV data.
We read the JSON data from a file using fs.readFileSync
. We then pass the JSON data to the jsonToCsv
function to get the CSV data. Finally, we write the CSV data to a file using fs.writeFileSync
.
Note that this code assumes that the JSON data is an array of objects with consistent keys. If the JSON data is not consistent, you may need to modify the code to handle the differences.
gistlibby LogSnag