Search code examples
javascriptsplitquotes

Make split() method in javascript create array using double quotes instead of single quotes


I've searched online a lot, but did not find anything. The questions here seem to address mostly php, so hopefully someone can help me with javascript.

Basically I am reading a text file and converting every line into a JSON object. I use .split() to turn the line into an array. However, when I do that, the array encloses the individual strings in single quotes. When I print the resulting object, it also has the values in single quotes. However I need them to be in double quotes for JSON. This might be a really stupid problem, or not a problem at at all, but I was not sure how to go about it. My code and terminal output are below.

Thank you in advance!!

lineReader.open('test.txt', function(reader){
    num=0;
    while (reader.hasNextLine()){
        reader.nextLine(function(line){
            //console.log(line);
            line = line.toLowerCase();
            lineArr = line.split('","');
            //console.log(lineArr);

            var last = lineArr.length - 1;
            lineArr[0] = lineArr[0].slice(1);
            lineArr[last] = lineArr[last].replace('"\r', '');
            if (lineArr[last].slice(-1) === '"'){
                lineArr[last] = lineArr[last].replace('"', '');
            };
            //console.log(lineArr);
            if(lineArr[0] === 'Name'){
                biz['Columns'] = lineArr;
            } else{
                var id = 'biz-' + num
                biz[id] = {
                    "value": {
                        "name": lineArr[0],
                        "address": lineArr[1],
                        "city": lineArr[2],
                        "province": lineArr[3],
                        "postal": lineArr[4]                    }
                };
            };
        });
        num++;
    }
    console.log(biz);
});

Output:

{ 'biz-0': 
   { value: 
      { name: 'name',
        address: 'address',
        city: 'city',
        province: 'province',
        postal: 'postal code' } } }

Solution

  • I'd suggest not attempting to build your own parser... use JSON.parse() and/or JSON.stringify(); instead. If you need to support older IE versions (or are forced to render in quirks mode)... include Crockford's json2.js https://github.com/douglascrockford/JSON-js