-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)
  });
}]);
2
  • hey lxe , i have added the piece of code i have had Commented Mar 20, 2016 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: papaparse.com Commented Mar 20, 2016 at 22:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

My input happens to also have \r\n which this doesn't account for. Any idea how to handle this?
You can use a regex in the split. See here: stackoverflow.com/questions/10805125/…
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.