DEV Community

Discussion on: Table to json with jq and awk

Collapse
 
jdforsythe profile image
Jeremy Forsythe • Edited

I find scripting languages to be much easier to write this stuff in and easier to fix later.

const fs = require('fs');
const data = fs.readFileSync('./FILE.txt').toString();
const lines = data.split('\n');
const json = lines.reduce((acc, l) => {
  const kv = l.split(' ');
  acc[kv[0]] = kv[1];
  return acc,
}, {});
fs.writeFileSync('./file.json', JSON.stringify(json, undefined, 2));

You can also just use the Node REPL for one-off conversions. I use this pattern for CSV to JSON all the time, which would be a nightmare using awk.

Collapse
 
foursixnine profile image
Santiago Zarate

I guess something similar could be done in Perl, Ruby or any other language capable of reading files and with json object representation capabilities. Thing is, I end up using awk a lot, for many things. But I'll keep your idea in hand and maybe update with a easier to follow $script version. If I ever have to do that again :)