如何在javascript中将文本文件转换为json

时间:2016-03-20 22:11:13

标签: javascript json

我有一个类似下面的文本文件

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

我需要转换为json,如下面的格式

[{"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"}]

用于javascript应用程序。

myapp.controller('TCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('list.txt').success(function(data) {
    $scope.todos = JSON.parse(data);
    //console.log(data)
  });
}]);

1 个答案:

答案 0 :(得分:2)

1)通过在回车符(行)上拆分字符串来获取单元格数组,然后使用map根据空格上的行拆分返回一个新数组。

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

2)标题是cells中的第一个嵌套数组。

var headings = cells.shift();

3)map在单元格上构建并根据值返回一个新对象。

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)对返回的对象进行字符串化。

var json = JSON.stringify(obj);

输出

[
  {
    "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