-2

I have a text file like the one below

id      nm              lat         lon         countryCode
819827  Razvilka        55.591667   37.740833   RU
524901  Moscow          55.752220   37.615555   RU
1271881 Firozpur        27.799999   76.949997   IN

i need to to convert to json like the format below

[{"id":819827,"nm":"Razvilka","lat":55.591667,"lon":37.740833,"countryCode":"RU"},
{"id":524901,"nm":"Moscow","lat":55.752220,"lon":37.615555,"countryCode":"RU"},
{"id":1271881,"nm":"Firozpur","lat":27.799999,"lon":76.949997,"countryCode":"IN"}]

for a javascript application.

myapp.controller('TCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('list.txt').success(function(data) {
    $scope.todos = JSON.parse(data);
    //console.log(data)
  });
}]);
Ezhil
  • 389
  • 1
  • 4
  • 18
  • hey lxe , i have added the piece of code i have had – Ezhil Mar 20 '16 at 22:27
  • There isn't a standard way to do what you want, but you can use a csv parsing library, like this one: http://papaparse.com/ – lxe Mar 20 '16 at 22:32

1 Answers1

10

1) Get an array of cells by splitting the string on the carriage return (rows), then using map to return an new array based on the row split on the spaces.

var cells = str.split('\n').map(function (el) { return el.split(/\s+/); });

2) Headings are the first nested array in cells.

var headings = cells.shift();

3) map over the cells building and returning a new object based on the values.

var obj = cells.map(function (el) {
  var obj = {};
  for (var i = 0, l = el.length; i < l; i++) {
    obj[headings[i]] = isNaN(Number(el[i])) ? el[i] : +el[i];
  }
  return obj;
});

4) Stringify the returned object.

var json = JSON.stringify(obj);

OUTPUT

[
  {
    "id": 819827,
    "nm": "Razvilka",
    "lat": 55.591667,
    "lon": 37.740833,
    "countryCode": "RU"
  },
  {
    "id": 524901,
    "nm": "Moscow",
    "lat": 55.75222,
    "lon": 37.615555,
    "countryCode": "RU"
  },
  {
    "id": 1271881,
    "nm": "Firozpur",
    "lat": 27.799999,
    "lon": 76.949997,
    "countryCode": "IN"
  }
]

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
  • My input happens to also have \r\n which this doesn't account for. Any idea how to handle this? – Urasquirrel Jul 28 '19 at 23:30
  • You can use a regex in the split. See here: https://stackoverflow.com/questions/10805125/how-to-remove-all-line-breaks-from-a-string – Andy Jul 29 '19 at 08:22
  • Your solution works great, thank you! But I have a problem with empty lines (e.g. on the end of an exported txt-file). How do I achieve this to remove or skip any empty lines within your code? – quantatheist Jul 22 '21 at 12:53