codingChicken
codingChicken

Reputation: 311

How to convert lines of text to JSON Lines?

If you have a text file with many lines of text, is there a readily available way to convert it into the JSON Lines format?

Example text file contains:

This is the first line.
This is the "second" line.
This is the \third/ line.
This is the {fourth} line;

Example JSON Lines (.jsonl) file:

{"text": "This is the first line."}
{"text": "This is the \"second\" line."}
{"text": "This is the \\third\/ line."}
{"text": "This is the {fourth} line;"}

I was hoping there is a simple way to sort of linearly transform it like this, while escaping the special characters for JSON. Are there online or (CLI) tools for the Mac that can do this?

Upvotes: 0

Views: 1838

Answers (1)

cyco130
cyco130

Reputation: 4934

A browser is the most handy way to access an interpreter nowadays. Here's a quick solution based on that:

Copy and paste your lines into this page: https://codebeautify.org/javascript-escape-unescape

Then copy the escaped string, press F12 on a modern broser and paste the following code:

console.log(JSON.stringify("***PASTE HERE**".split("\n").map(x => ({text: x}))))

Then delete ***PASTE HERE*** and paste the escaped lines. Press enter and you'll have a JSON output similar to what you want.

Upvotes: 1

Related Questions