1 minute to read - Apr 12, 2023

Convert JSONL into JSON array

Write a nodejs script to turn a jsonl file into a json array

Sure! Here is a simple script that reads a JSONL (JSON Lines) file and converts it into a JSON array:

Copy code

`const fs = require('fs'); // Read the JSONL file const jsonl = fs.readFileSync('input.jsonl', 'utf8'); // Split the file into an array of lines const lines = jsonl.split('\n'); // Remove the last line if it's empty (it happens when the file doesn't end with a newline) if (lines[lines.length - 1] === '') { lines.pop(); } // Parse each line as a JSON object and add it to the array const array = lines.map(JSON.parse); // Write the array to a new file fs.writeFileSync('output.json', JSON.stringify(array, null, 2));`

This script reads the input file `input.jsonl`, splits it into an array of lines, removes the last line if it's empty, and then parses each line as a JSON object. Finally, it writes the resulting array to a new file `output.json`.

I hope this helps! Let me know if you have any questions.

loading...