krikara
krikara

Reputation: 2435

Convert text file into clean JSON format

I want to read a text file and write a text file in a clean JSON format.

My text file looks like this

Version:2
TaxiStation:6072
TaxiLicense:EM9543
System_ID:910

When I use the following:

data2= JSON.stringify(data2, null, position+1);
fs.writeFile(dirarray[0], data2, function(err) { ...

My output always comes out ugly : "Version:2\r\nTaxiStation:6072\r\nTaxiLicense:EM8378\r\n

Ideally, I would want to make my text file formatted nicely. Is it possible to achieve this?

{
   "Version":2,
   "TaxiStation":6072,
   "TaxiLicense":"EM9543",
   "System_ID":910
}

Upvotes: 2

Views: 13890

Answers (2)

Enrichman
Enrichman

Reputation: 11337

The main problem is that the stringify function will take a js object and jsonize it, but your file is not an object, or array, or anything, so, once read, it's interpreted like a single string. And so it's parsed as a string!

From your file you should create a js object matching your lines and then parse it.

This is a working example: http://pastebin.com/EhnhNUyB

The main part is here

dataArr = data2.split('\n');

var obj = {};

for (i=0;i<dataArr.length;i++) {
    keyVal = dataArr[i].split(":");

    var key = keyVal[0];

    var val;
    if(isInt(keyVal[1])) {
        val = parseInt(keyVal[1]);
    } else {
        val = keyVal[1];
    }
    obj[key] = val;
}

data2 = JSON.stringify(obj, null, 4);

as you can see I've created a new object and pushed to it the new key-values.

Upvotes: -1

Mikuso
Mikuso

Reputation: 1350

Use something like this to transform your data before you stringify it:

data2 = data2.split(/\r?\n/).reduce(function(m,i){
    var s = i.split(':');
    m[s.shift()] = s.join(':');
    return m;
}, {});

JSON.stringify(data2);

Upvotes: 3

Related Questions